c - 使用管道在两个 child 进程之间持续通信

c - continously communicate between two child processes using pipes

刚开始学习管道(一般来说是 IPC)。在我浏览了一些手册页、网站和一些 SO 问题之后,比如 this, This 和其他一些问题。我了解了基础知识,我看到这种通信只完成一次,即 parent 写入 child 并且 child 读取它或 parent 和 child 相互读写一次,然后管道关闭。

我想要的是在不关闭管道的情况下保持进程之间的这种通信,即, 比如说,我的程序有 2 个 child 进程,其中第一个 child 进程是 运行 一个 while 循环中的东西,第二个是 运行 一个连续的计时器。在特定的时间间隔,我的第二个进程将一些 'signal' 发送到第一个 child 并且我的第一个进程在那一刻停止并打印一些东西并再次重新启动以进行下一次计时器停止。 (<-这是我使用线程完成的)

这是我作为示例试用的程序。但是我无法保持通信连续。

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

int main(void)
{
    int     fd[2], nbytes, count = 5;
    pid_t   childpid;
    char    string[] = "Hello, world!\n";
    char    readbuffer[80];

    if((childpid = fork()) == -1)
    {
            perror("fork");
            exit(1);
    }

    if(childpid == 0)
    {
            /* Child process closes up input side of pipe */


            /* Send "string" through the output side of pipe */
            while(count--)
            {
                pipe(fd);
                close(fd[0]);
                write(fd[1], string, (strlen(string)+1));
                close(fd[1]);
            }
            exit(0);
    }
    else
    {
            /* Parent process closes up output side of pipe */
            while(count--)
            {
                pipe(fd);
                close(fd[1]);

            /* Read in a string from the pipe */
            nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
            printf("Received string: %s\n", readbuffer);
            close(fd[0]);
            close(fd[1]);
            }
    }
    int status;
    waitpid(getppid(), &status, 0);

    printf("Done!\n");

    return(0);

}

从这些例子中,我推断管道在每次 send/read 后都会关闭。 每次都尝试打开新的管道,还是打不开

任何人都可以帮助我我缺少什么或我应该做什么?

现在父进程和子进程都创建了自己的一对管道,其他进程不知道。

应该在父进程中创建管道,然后 fork。

此外,您在循环中关闭管道 的 reading/writing 端,此时您应该在循环后关闭它们,此时所有的通信都已完成。


还有一个不相关的小问题...

在 reader 中你应该真正循环而 read 不 return 0 (然后管道的写端关闭)或 -1(如果有错误)。

如果您使用共享内存方法,那就太好了。在这种方法中,父进程将分配一个内存区域,该内存区域将在所有进程之间共享。使用锁来保护您的资源,即共享内存。您还可以访问此 answer,其中详细说明了背后的概念。还要记住,在共享内存方法中,通信可以是 many-to-many。但如果是管道,则为 one-to-one。 干杯, K. Infoginx.com