![](/img/trans.png)
[英]boost::asio with named pipes; parent process can't read from pipe via async_read_some
[英]Parent process doesn't read form pipe
我有這樣的事情:
pipe
close(pipe[0]);
parent writes something to pipe
close(pipe[1]);
fork();
if(child)
{
close(pipe[1]);
child reads from pipe
close(pipe[0]);
child does some operations
child writes to pipe
close(pipe[1]);
}
else
{
back to parent
close(pipe[0]);
wait(&code);
parent tries to read what the terminated child just wrote but fails to do so
}
我不知道如何讓父母從被終止的孩子那里讀書。 我需要使用dup
嗎? 我不太確定dup
或dup2
在什么情況下有用。
使用write()
和read()
函數完成write()
和read()
。
我必須使用管道而不是fifo或其他方法在進程之間進行通信。
我認為你需要的是fifo
套件,我認為你也不需要使用dup
。 這是一個有效的代碼:
#include <fcntl.h>
int main()
{
int e=open("fif",O_RDONLY|O_NONBLOCK);
if(fork()==0)
{
int d=open("fif",O_WRONLY);
write(d,"hi there\n",9);
close(d);
//sleep(5);
exit(0);
}
wait();
char buf[15];
int n=read(e,buf,15);
buf[n]=0;
printf("%s", buf);
//wait();
return 0;
}
本文的一個示例說:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
main()
{
int fd[2];
pid_t childpid;
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
}
.
.
}
IIRC就是這樣做的。 關鍵是關閉父子進程中未使用的fd。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.