简体   繁体   English

结合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);
  }
}

I have this piece of code but for some reason when I execute it, the procces freezes with no print and with no exit(i have to press CTRL+C). 我有这段代码,但是由于某种原因,执行该过程时,过程冻结,没有打印且没有退出(我必须按CTRL + C)。 Any idea why? 知道为什么吗? I tried the same thing, but using internal pipe and it worked. 我尝试了同样的事情,但是使用内部管道,它起作用了。

It works perfect if I remove wait(NULL) from the parent process. 如果我从父进程中删除了wait(NULL),它将非常完美。 But I don't really know why. 但是我真的不知道为什么。

From the man mkfifo : 来自男子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. 以这种方式创建FIFO特殊文件后,任何进程都可以以与普通文件相同的方式打开该文件以进行读取或写入。 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. 打开FIFO以正常读取块,直到其他进程打开相同的FIFO进行写入为止,反之亦然。

The parent process waits in wait(NULL) for the child finish, but the child waits for someone to open "view" on the other end after the call open("view",O_WRONLY) . 父进程在wait(NULL)wait(NULL)子进程完成,但是子进程在调用open("view",O_WRONLY)之后等待另一端打开某个"view"


To have a valid null terminated string you also need to initialize resp by zero char resp[100] = { 0 }; 要获得有效的以null终止的字符串,您还需要通过零char resp[100] = { 0 };来初始化resp char resp[100] = { 0 }; or put zero at the end of read output: 或在读取输出的末尾放置零:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM