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/