gpt4 book ai didi

c - 为什么我的 Fork 子进程不从管道读取?

转载 作者:行者123 更新时间:2023-11-30 16:45:14 25 4
gpt4 key购买 nike

我正在尝试使用 fork() 创建一个单独的“记录器”进程,该进程会在收到消息时将消息记录到文件中。然而我遇到了一个问题,子进程似乎在一个字符串后“放弃”。

我什至不确定这是否是一个记录器进程的好方法 - 但这里是输出和代码

任何想法或帮助将不胜感激 - 谢谢

https://i.imgur.com/Mg7Jkzi.png

int main()
{
int pipefd[2], nbytes;
pid_t pid;
char szLogtest[] = "Log Event: Blah blah blah\n";
char szLogtest2[] = "Log Event: Blah blah 2\n";
char readbuffer[512];

pipe(pipefd);

if ((pid = fork()) == -1)
{
fprintf(stderr, "Fork error!\n");
exit(1);
}
else if (pid == 0)
{
printf("I am child!\n");
close(pipefd[1]); // close the write end of pipe

while(1)
{
nbytes = read(pipefd[0], readbuffer, sizeof(readbuffer));
printf("Nbytes is %d\n", nbytes);
if (nbytes)
{
printf("Received string: %s", readbuffer);
}

nbytes = 0;
}

}
else
{
printf("I am parent!\n");
close(pipefd[0]); //close read end of pipe

write(pipefd[1], szLogtest, (strlen(szLogtest)+1));
write(pipefd[1], szLogtest2, (strlen(szLogtest2)+1));
}

return 0;
}

最佳答案

评论中的正确诊断

Ian Abbot 正确诊断在 comment ,直接的问题是您在消息中间收到了空字节,但试图将消息视为字符串。这切断了信息。

您还从 sizzzzlerz 得到了明智的建议在 comment .

不要发送空字节

最简单的解决方法是不向子级发送空字节。那么子进程如何分割读取并不重要,除非它将信息添加到日志打印中(例如时间信息)。这是一个例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

static void wait_for(pid_t pid)
{
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
{
printf("%d: PID %d exit status 0x%.4X\n", (int)getpid(), corpse, status);
if (corpse == pid)
break;
}
}

static void write_log(int fd, const char *msg)
{
ssize_t len = strlen(msg);
if (write(fd, msg, len) != len)
{
fprintf(stderr, "%d: failed to write message to logger\n", (int)getpid());
exit(EXIT_FAILURE);
}
printf("%d: Wrote: %zd [%s]\n", (int)getpid(), len, msg);
}

int main(void)
{
int pipefd[2];
pid_t pid;
char szLogtest1[] = "Log Event: Blah blah blah\n";
char szLogtest2[] = "Log Event: Blah blah 2\n";

pipe(pipefd);

if ((pid = fork()) == -1)
{
fprintf(stderr, "Fork error!\n");
exit(1);
}
else if (pid == 0)
{
printf("%d: I am child!\n", (int)getpid());
close(pipefd[1]); // close the write end of pipe

while (1)
{
char readbuffer[512];
int nbytes = read(pipefd[0], readbuffer, sizeof(readbuffer));
if (nbytes <= 0)
{
close(pipefd[0]);
printf("EOF on pipe -exiting\n");
exit(EXIT_SUCCESS);
}
printf("%d: Logging string: %d [%s]\n", (int)getpid(), nbytes, readbuffer);
}
}
else
{
printf("%d: I am parent!\n", (int)getpid());
close(pipefd[0]); // close read end of pipe

write_log(pipefd[1], szLogtest1);
write_log(pipefd[1], szLogtest2);
close(pipefd[1]);
wait_for(pid);
}

return 0;
}

请注意,大多数消息都以生成该消息的进程的 PID 为前缀。它可以更轻松地查看多进程调试中发生的情况。

该程序的示例输出 (log61):

$ ./log61
48941: I am parent!
48941: Wrote: 26 [Log Event: Blah blah blah
]
48941: Wrote: 23 [Log Event: Blah blah 2
]
48942: I am child!
48942: Logging string: 49 [Log Event: Blah blah blah
Log Event: Blah blah 2
]
EOF on pipe -exiting
48941: PID 48942 exit status 0x0000
$

给消息加上长度前缀

另一个简单(但不是那么简单)的修复是将消息分成不超过 255 字节的 block ,并写入 1 字节长度,后跟那么多字节的数据。然后子进程读取 1 字节长度和那么多字节的数据。此代码创建一个与 write_log() 函数并行的 read_log() 函数,并且 write_log() 函数也被修改。

#include <assert.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

static void wait_for(pid_t pid)
{
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
{
printf("%d: PID %d exit status 0x%.4X\n", (int)getpid(), corpse, status);
if (corpse == pid)
break;
}
}

static void write_log(int fd, const char *msg)
{
ssize_t len = strlen(msg);
unsigned char byte = len;
assert(len > 0 && len <= UCHAR_MAX);

if (write(fd, &byte, sizeof(byte)) != sizeof(byte) ||
write(fd, msg, len) != len)
{
fprintf(stderr, "%d: failed to write message to logger\n", (int)getpid());
exit(EXIT_FAILURE);
}
printf("%d: Wrote: %zd [%s]\n", (int)getpid(), len, msg);
}

static int read_log(int fd, size_t buflen, char buffer[buflen])
{
unsigned char byte;
if (read(fd, &byte, sizeof(byte)) != sizeof(byte))
{
fprintf(stderr, "%d: EOF on file descriptor %d\n", (int)getpid(), fd);
return 0;
}
if (buflen < (size_t)(byte + 1)) // avoid signed/unsigned comparison
{
fprintf(stderr, "%d: buffer length %zu cannot hold %d bytes\n",
(int)getpid(), buflen, byte + 1);
exit(EXIT_FAILURE);
}
if (read(fd, buffer, byte) != byte)
{
fprintf(stderr, "%d: failed to read %d bytes from file descriptor %d\n",
(int)getpid(), byte, fd);
exit(EXIT_FAILURE);
}
buffer[byte] = '\0';
return byte;
}

int main(void)
{
int pipefd[2];
pid_t pid;
char szLogtest1[] = "Log Event: Blah blah blah\n";
char szLogtest2[] = "Log Event: Blah blah 2\n";

pipe(pipefd);

if ((pid = fork()) == -1)
{
fprintf(stderr, "Fork error!\n");
exit(1);
}
else if (pid == 0)
{
printf("%d: I am child!\n", (int)getpid());
close(pipefd[1]); // close the write end of pipe

char readbuffer[512];
int nbytes;
while ((nbytes = read_log(pipefd[0], sizeof(readbuffer), readbuffer)) > 0)
{
printf("%d: Logging string: %d [%s]\n", (int)getpid(), nbytes, readbuffer);
}
close(pipefd[0]);
printf("EOF on pipe -exiting\n");
exit(EXIT_SUCCESS);
}
else
{
printf("%d: I am parent!\n", (int)getpid());
close(pipefd[0]); // close read end of pipe

write_log(pipefd[1], szLogtest1);
write_log(pipefd[1], szLogtest2);
close(pipefd[1]);
wait_for(pid);
}

return 0;
}

该程序的示例输出 (log59):

$ ./log59
48993: I am parent!
48993: Wrote: 26 [Log Event: Blah blah blah
]
48993: Wrote: 23 [Log Event: Blah blah 2
]
48994: I am child!
48994: Logging string: 26 [Log Event: Blah blah blah
]
48994: Logging string: 23 [Log Event: Blah blah 2
]
48994: EOF on file descriptor 3
EOF on pipe -exiting
48993: PID 48994 exit status 0x0000
$

如您所见,单独的消息是单独记录的,这与第一个示例中的 union 消息传递不同。

对很长的消息进行编码

如果将长消息作为一个单元处理是至关重要的,但它们相当罕见,您可以发送 1..254 作为单个单元消息的长度,并发送 255 来指示“后面跟着 254 字节 block ,但是它不完整'。或者,实际上,您可以发送 1..255 来指示最多 255 字节的完整消息,发送 0 来指示“这是长度超过 255 字节的消息的下一个 255 字节分期”。 (请注意,您只能发送 255 个字节,以便有至少 1 个字节的后续消息。)这会修改 write_log()read_log() 函数,但主要代码不必​​更改 - 除了需要测试多 block 功能之外。

此代码比以前的版本更复杂。它显示了一些被注释掉的调试打印。

/* SO 4481-0272 */
/* Variant 3 - handle long messages */
#include <assert.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

static void wait_for(pid_t pid)
{
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
{
printf("%d: PID %d exit status 0x%.4X\n", (int)getpid(), corpse, status);
if (corpse == pid)
break;
}
}

static void write_log_segment(int fd, size_t lencode, size_t length, const char *msg)
{
unsigned char byte = lencode;
assert(lencode == length || (lencode == 0 && length == UCHAR_MAX));

if (write(fd, &byte, sizeof(byte)) != sizeof(byte) ||
write(fd, msg, length) != (ssize_t)length) // avoid signed/unsigned comparison
{
fprintf(stderr, "%d: failed to write message to logger\n", (int)getpid());
exit(EXIT_FAILURE);
}
//printf("%d: Wrote segment: %zu (code %zu) [%s]\n", (int)getpid(), length, lencode, msg);
}

static void write_log(int fd, const char *msg)
{
size_t len = strlen(msg);
printf("%d: Write buffer: %zu [%s]\n", (int)getpid(), len, msg);
while (len > 0)
{
size_t lencode = (len <= UCHAR_MAX) ? len : 0;
size_t length = (len <= UCHAR_MAX) ? len : UCHAR_MAX;
write_log_segment(fd, lencode, length, msg);
len -= length;
msg += length;
}
//printf("%d: Buffer complete\n", (int)getpid());
}

/*
** This code could encounter:
** 1. EOF (or a read error) - return EOF.
** 2. A regular complete message in a single segment - return message
** length (1..255).
** 3. A partial message with more segments to follow - return MSG_SEGMENT.
** Partial segments with more to follow are of length 255, but it is
** possible to have a regular complete message of length 255.
*/
enum { MSG_SEGMENT = -2 };
static_assert(MSG_SEGMENT != EOF, "EOF is not distinct from MSG_SEGMENT");

static int read_log_segment(int fd, size_t buflen, char buffer[buflen])
{
unsigned char byte;
if (read(fd, &byte, sizeof(byte)) != sizeof(byte))
{
fprintf(stderr, "%d: EOF on file descriptor %d\n", (int)getpid(), fd);
return EOF;
}
size_t length = byte;
if (length == 0)
length = UCHAR_MAX;
if (buflen < (size_t)(byte + 1)) // avoid signed/unsigned comparison
{
fprintf(stderr, "%d: buffer length %zu cannot hold %d bytes\n",
(int)getpid(), buflen, byte + 1);
exit(EXIT_FAILURE);
}
if (read(fd, buffer, length) != (ssize_t)length) // avoid signed/unsigned comparison
{
fprintf(stderr, "%d: failed to read %zu bytes from file descriptor %d\n",
(int)getpid(), length, fd);
exit(EXIT_FAILURE);
}
buffer[length] = '\0';
return (byte == 0) ? MSG_SEGMENT : byte;
}

static size_t read_log(int fd, size_t buflen, char buffer[buflen])
{
//printf("%d: reading %zu\n", (int)getpid(), buflen);
char *msg = buffer;
size_t len = buflen;
int nbytes;
int tbytes = 0;
while (len > 0 && (nbytes = read_log_segment(fd, len, msg)) != EOF)
{
if (nbytes != MSG_SEGMENT)
{
tbytes += nbytes;
break;
}
nbytes = UCHAR_MAX;
//printf("%d: segment %d [%s] (%zu: %d: %zu)\n", (int)getpid(), nbytes, msg, buflen, tbytes, len);
msg += nbytes;
len -= nbytes;
tbytes += nbytes;
}
/* This disguises a read error or EOF as success when a long message is truncated */
//if (tbytes != 0)
// printf("%d: logging %d [%s]\n", (int)getpid(), tbytes, buffer);
//else
// printf("%d: EOF\n", (int)getpid());
return tbytes;
}

static void gen_msg(size_t size, char *buffer)
{
enum { CHUNK_SIZE = 64 };
//char *obuffer = buffer; // DEBUG
//size_t osize = size; // DEBUG
char c = 'a';
while (size >= CHUNK_SIZE)
{
memset(buffer, c, CHUNK_SIZE - 1);
buffer[CHUNK_SIZE - 1] = '\n';
size -= CHUNK_SIZE;
buffer += CHUNK_SIZE;
if (++c > 'z')
c = 'a';
}
if (size > 0)
{
if (size > 1)
memset(buffer, '@', size - 1);
buffer[size - 1] = '\n';
buffer += size;
}
buffer[0] = '\0';
//printf("GM: Buffer %zu (%zu) [%s]\n", osize, strlen(obuffer), obuffer); // DEBUG
}

int main(void)
{
int pipefd[2];
pid_t pid;
char szLogtest1[] = "Log Event: Blah blah blah\n";
char szLogtest2[] = "Log Event: Blah blah 2\n";

pipe(pipefd);

if ((pid = fork()) == -1)
{
fprintf(stderr, "Fork error!\n");
exit(1);
}
else if (pid == 0)
{
printf("%d: I am child!\n", (int)getpid());
close(pipefd[1]); // close the write end of pipe

char readbuffer[1200];
int nbytes;
while ((nbytes = read_log(pipefd[0], sizeof(readbuffer), readbuffer)) > 0)
{
printf("%d: Logging string: %d [%s]\n", (int)getpid(), nbytes, readbuffer);
}
close(pipefd[0]);
printf("%d: EOF on pipe - exiting\n", (int)getpid());
exit(EXIT_SUCCESS);
}
else
{
printf("%d: I am parent!\n", (int)getpid());
close(pipefd[0]); // close read end of pipe

write_log(pipefd[1], szLogtest1);
write_log(pipefd[1], szLogtest2);
char buffer[1100];
gen_msg(290, buffer);
write_log(pipefd[1], buffer);
gen_msg(842, buffer);
write_log(pipefd[1], buffer);
//int multiplier = 4;
//for (int i = 64; i <= 1024; i *= multiplier)
//{
// char buffer[1100];
// //for (int j = i - multiplier; j <= i + multiplier; j++)
// for (int j = i - 1; j <= i + 1; j++)
// {
// gen_msg(j, buffer);
// write_log(pipefd[1], buffer);
// }
//}
close(pipefd[1]);
wait_for(pid);
}

return 0;
}

该程序的示例输出 (log67):

50183: I am parent!
50183: Write buffer: 26 [Log Event: Blah blah blah
]
50183: Write buffer: 23 [Log Event: Blah blah 2
]
50183: Write buffer: 290 [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
]
50183: Write buffer: 842 [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll
mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
@@@@@@@@@
]
50184: I am child!
50184: Logging string: 26 [Log Event: Blah blah blah
]
50184: Logging string: 23 [Log Event: Blah blah 2
]
50184: Logging string: 290 [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
]
50184: Logging string: 842 [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll
mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
@@@@@@@@@
]
50184: EOF on file descriptor 3
50184: EOF on pipe - exiting
50183: PID 50184 exit status 0x0000

关于c - 为什么我的 Fork 子进程不从管道读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44180272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com