首页 > 解决方案 > 关于父进程使用简单管道向子进程写入消息的说明

问题描述

这是一个 C 程序,其中父进程尝试使用简单的管道将消息写入其子进程。得到预期的输出。

根据代码,父进程调用wait(),一直等到子进程退出(返回)。

另外,子进程调用read(),它等待通过另一个管道端写入一些东西?

因此,两个进程不应该一直相互等待并导致死锁吗?该程序如何正常运行?

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MSGSIZE 16
char *msg1 = "Hello,Once";
char *msg2 = "Hello,Twice";
char *msg3 = "Hello,Thrice";
int main()
{
    char buff[MSGSIZE];
    int pi[2],pid,nbytes;
    if(pipe(pi) < 0) _exit(1);
    if((pid=fork()) > 0)
    {
        close(pi[0]);
        write(pi[1],msg1,MSGSIZE);
        write(pi[1],msg2,MSGSIZE);
        write(pi[1],msg3,MSGSIZE);
        close(pi[1]); 
        wait(NULL);
    }
    else
    {
        close(pi[1]);
        while((nbytes = read(pi[0],buff,MSGSIZE)) > 0) printf("%s\n",buff);
        printf("Reading Completed\n");
        close(pi[0]);
        if(nbytes != 0) _exit(2);
        
    }   
    return 0;
}

标签: clinuxoperating-systempipeipc

解决方案


推荐阅读