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

标签 c linux pipe ipc

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

我想要的是在不关闭管道的情况下保持进程之间的通信,即 比如说,我的程序有 2 个子进程,其中第一个子进程在 while 循环中运行某些东西,第二个子进程连续运行一个计时器。在特定的时间间隔,我的第二个进程向第一个 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);

从这些例子中,我推断管道在每次发送/读取后都会关闭。 我每次都尝试打开新管道,但还是无法打开。

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

最佳答案

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

应该在父进程 fork 之前创建管道。

此外,您还可以在循环中关闭管道的读/写端,当您应该在循环后关闭它们时,即所有通信都已完成时。


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

在阅读器中,当 read 不返回 0(然后管道的写入端关闭)或 -1< 时,您应该真正循环(如果有错误)。

关于c - 使用管道在两个子进程之间持续通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38104214/

相关文章:

c - 通过超时或使用同一模块中的另一个函数写入其文件描述符来中断选择函数

c - 管道实现停留在 dup2 命令

c - 将第一个字节设置为 0 或使用 memset 到 "reset"整个缓冲区

c - 如何仅循环遍历来自 select() 的 fd_set 结果的事件文件描述符?

c - ld 返回 1 退出状态,斐波那契搜索

linux - Rpm 安装错误,libstdc++-4.4.4-13.el6

python - 这是在 Python 中运行 shell 脚本的正确方法吗?

linux - 将菜单项添加到 GNOME 菜单或 Unity

检查 C 编程代码

c++ - C 中信号量的使用?