Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 从管道读取的父级-什么条件_C_Unix_Pipe - Fatal编程技术网

C 从管道读取的父级-什么条件

C 从管道读取的父级-什么条件,c,unix,pipe,C,Unix,Pipe,我有一个程序,在那里孩子们向管道发送信息:“你好”和“goodbay”。他们发送hello,然后以秒为单位随机睡眠。醒来后,他们发送“goodbay”。 我想,我的问题是,家长只看了一次管道,然后就完成了工作。我想它必须经常检查管道。。。有人能帮我吗 我的代码: void child_work(int pipe) { int tt; char mb[PIPE_BUF]; snprintf(mb,PIPE_BUF,"Pid[%d]: Hello\n",getpid());

我有一个程序,在那里孩子们向管道发送信息:“你好”和“goodbay”。他们发送hello,然后以秒为单位随机睡眠。醒来后,他们发送“goodbay”。 我想,我的问题是,家长只看了一次管道,然后就完成了工作。我想它必须经常检查管道。。。有人能帮我吗

我的代码:

void child_work(int pipe)
{
    int tt;
    char mb[PIPE_BUF];

    snprintf(mb,PIPE_BUF,"Pid[%d]: Hello\n",getpid());
    if (-1 == TEMP_FAILURE_RETRY (write (pipe, mb, strlen(mb))))ERR ("write");

    for(tt=5;tt>0;tt=sleep(tt));

    snprintf(mb,PIPE_BUF,"Pid[%d]: Goodbye\n",getpid());
    if (TEMP_FAILURE_RETRY (write (pipe, mb, (strlen(mb)+1)))<0)ERR ("write");
    kill(getpid(),SIGTERM);
}

void parent_work(int pipe)
{
    char buffer[PIPE_BUF];  
    int result;

   do
{
    result=TEMP_FAILURE_RETRY(read(pipe, buffer,sizeof(buffer)));
    if(result<0)ERR("read");
    if(result>0)printf("%s\n", buffer); 

}while(result>0);

    while((TEMP_FAILURE_RETRY(wait(NULL)))>0);
}
无效子项工作(内部管道)
{
int-tt;
char mb[PIPE_BUF];
snprintf(mb,PIPE_BUF,“Pid[%d]:Hello\n”,getpid());
如果(-1==TEMP_FAILURE_RETRY(写入(管道,mb,strlen(mb)))错误(“写入”);
对于(tt=5;tt>0;tt=sleep(tt));
snprintf(mb,PIPE_BUF,“Pid[%d]:再见\n”,getpid());
如果(临时失败重试(写入(管道,mb,(strlen(mb)+1)))0;
而((临时失败重试(等待(空))大于0);
}

中设置的(…read(…buffer)
在循环的下一次迭代中被
result=read(…buffer….
覆盖。父循环正在从循环中的管道读取。这应该足够了。代码不应该编译。在(…wait..
它正在等待子进程的结束。它可以被删除。我认为,问题是缓冲区没有清理,父进程甚至从管道中读取旧消息。问题是您没有显示实际执行的代码。问题中带有
read
的代码打印
缓冲区一次。是否重复如果您删除
TEMP\u FAILURE\u RETRY
round
write()
?I change on result=TEMP\u FAILURE\u RETRY(读取(管道、缓冲区、管道);…while(结果>0),但现在,相同的消息会被父级多次从管道中读取…使用新代码