gpt4 book ai didi

fork后创建管道

转载 作者:太空宇宙 更新时间:2023-11-04 05:20:53 26 4
gpt4 key购买 nike

这样做可能/正确吗?如果我从“子”进程的 fd1[1] 进行写入,那么可以从“父”进程的 fd2[0] 进行读取?

main(){
pid_t pid;
pid = fork();
if(pid <0){
return -1;
}
if(pid == 0){
int fd1[2];
int fd2[2];
pipe(fd1);
pipe(fd2);
close fd1[1];
close fd2[0];
//writes & reads between the fd1 pipes
//writes & reads between the fd2 pipes
}else{
int fd1[2];
int fd2[2];
pipe(fd1);
pipe(fd2);
close fd1[1];
close fd2[0];
//writes & reads between the fd1 pipes
//writes & reads between the fd2 pipes
}
}

最佳答案

不,用于在进程之间通信的管道应该在 fork() 之前创建(否则,您没有简单的方法通过它们发送,因为读取和写端应该被不同的进程使用)。

在进程之间发送文件描述符作为套接字上的带外消息有一些肮脏的技巧,但我真的忘记了细节,这很丑陋

关于fork后创建管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8947639/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com