结合 fork、fifo 和 execlp?

标签 c unix exec fork fifo

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)。 知道为什么吗?我尝试了同样的事情,但使用内部管道并且成功了。

最佳答案

来自男人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) 中等待子进程完成,但子进程等待有人在调用后打开另一端的 "view" 打开(“查看”,O_WRONLY)


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

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

关于结合 fork、fifo 和 execlp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33358301/

相关文章:

unix - Unix 中的用户无法运行 hadoop 命令

java - Ant: 没有那个文件或目录

php - mysqldump 停止新的 apache 升级

c - if 条件下发生了什么?

c - recvfrom 的延迟随它被调用的频率而变化

linux - UNIX 循环遍历 url 列表并使用 wget 保存

java - 如何通过Java执行cmd命令

c - 在 C 函数中测量时间

c - 通过fifo将curses输入发送到C中的另一个终端

bash - 首先使用 sed 替换文件中的字符串