鉴于此代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world! I'm the son and this my message!\n";
char readbuffer[80];
pipe(fd); // piping fd[0] & fd[1]
if((childpid = fork()) == -1) // here we create a SON process
{
perror("fork");
exit(1);
}
if(childpid == 0) // child process
{
/* Child process closes up input side of pipe */
close(fd[0]); // closing the READ end from reading , after that the SON would write into fd[1]
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
printf("Verification : Message was sent successfully by the SON!\n");
exit(0);
}
else // father process
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("I'm the father and I received that string: %s", readbuffer);
}
return(0);
}
输出是:
I'm the father and I received that string: Hello, world! I'm the son and this my message!
Verification : Message was sent successfully by the SON!
我正在尝试理解管道,但我不清楚一些事情:
如果儿子在那一行发送他的消息,
write(fd[1], string, (strlen(string)+1));
然后我们有printf
验证消息已发送,为什么我在父亲收到儿子的消息后Verification : Message was sent successfully by the SON!
得到验证(例如) ?不是应该先是儿子的验证,然后才是字符串吗?如果父亲试图从管道中读取而儿子想要写入管道,那么这里的某个地方隐藏了(我认为)一个死锁,不是吗?为什么我没有陷入僵局?
谢谢