叉子过程不从管道读取

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了叉子过程不从管道读取相关的知识,希望对你有一定的参考价值。

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

我甚至不确定这是否是一个很好的方法来进行记录器处理 - 但这是输出和代码

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

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

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

        pipe(pipefd);

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

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

                nbytes = 0;
            }

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

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

        return 0;
    }
答案

Correct diagnosis in comments

正如Ian Abbotcomment中正确诊断的那样,当前的问题是你在消息中间收到空字节,但是试图将消息视为字符串。这切碎了信息。

你也在sizzzzlerz得到comment的明智建议。

Do not send null bytes

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

#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
", (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
", (int)getpid());
        exit(EXIT_FAILURE);
    }
    printf("%d: Wrote: %zd [%s]
", (int)getpid(), len, msg);
}

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

    pipe(pipefd);

    if ((pid = fork()) == -1)
    {
        fprintf(stderr, "Fork error!
");
        exit(1);
    }
    else if (pid == 0)
    {
        printf("%d: I am child!
", (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
");
                exit(EXIT_SUCCESS);
            }
            printf("%d: Logging string: %d [%s]
", (int)getpid(), nbytes, readbuffer);
        }
    }
    else
    {
        printf("%d: I am parent!
", (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
$

Prefix messages with length

另一个简单(但不是那么简单)修复是将消息分成不超过255个字节的块,并写入1个字节的长度,然后写入那么多字节的数据。然后,孩子读取1字节长度和多个字节的数据。此代码创建一个与read_log()函数并行的write_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
", (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
", (int)getpid());
        exit(EXIT_FAILURE);
    }
    printf("%d: Wrote: %zd [%s]
", (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
", (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
",
                (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
",
                (int)getpid(), byte, fd);
        exit(EXIT_FAILURE);
    }
    buffer[byte] = '';
    return byte;
}

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

    pipe(pipefd);

    if ((pid = fork()) == -1)
    {
        fprintf(stderr, "Fork error!
");
        exit(1);
    }
    else if (pid == 0)
    {
        printf("%d: I am child!
", (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]
", (int)getpid(), nbytes, readbuffer);
        }
        close(pipefd[0]);
        printf("EOF on pipe -exiting
");
        exit(EXIT_SUCCESS);
    }
    else
    {
        printf("%d: I am parent!
", (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
$

如您所见,单独的消息是单独记录的,与第一个示例中的联合消息不同。

Encoding very long messages

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

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

/* 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
", (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
", (int)getpid());
        exit(EXIT_FAILURE);
    }
    //printf("%d: Wrote segment: %zu (code %zu) [%s]
", (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]
", (int)getpid(), len, msg);
    while (len > 0)
    {
        size

以上是关于叉子过程不从管道读取的主要内容,如果未能解决你的问题,请参考以下文章

创建片段而不从 java 代码实例化它

获取“分段错误核心转储”

[Go] 通过 17 个简短代码片段,切底弄懂 channel 基础

StreamWriter 在其包裹的 Pipe 未排空时无法关闭?

15种Python片段去优化你的数据科学管道

匙羹先生与叉子小姐餐饮店LOGO设计过程