结合 fork、fifo 和 execlp?

Combine fork,fifo and execlp?

int main(){
  mkfifo("view",0666);
  int pid = fork();
  if(pid==0){
    close(1);
    int fd = open("view",O_WRONLY);
    dup(fd);
    execlp("cat", "cat", "users", NULL);
    close(fd);
  }
  else{
    wait(NULL);
    int fd = open("view",O_RDONLY);
    char resp[100];
    read(fd,resp,20);
    printf("%s\n",resp);
    close(fd);
  }
}

我有这段代码,但由于某种原因,当我执行它时,过程冻结,没有打印也没有退出(我必须按 CTRL+C)。 知道为什么吗?我试过同样的东西,但使用内部管道并且有效。

如果我从父进程中删除 wait(NULL) ,它就完美了。但是我真的不知道为什么。

来自男人mkfifo:

Once you have created a FIFO special file in this way, any process can open it for reading or writing, in the same way as an ordinary file. However, it has to be open at both ends simultaneously before you can proceed to do any input or output operations on it. Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and vice versa.

父进程在 wait(NULL) 中等待子进程完成,但子进程在调用 open("view",O_WRONLY).[=18= 后等待另一端有人打开 "view" ]


要获得一个有效的空终止字符串,您还需要将 resp 初始化为零 char resp[100] = { 0 }; 或将零放在读取输出的末尾:

ssize_t size = read(fd,resp,20);
resp[size] = '[=10=]';