鉴于这种代码:在父子之间发送消息 - 为什么没有死锁?
#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!
)后父亲收到儿子的消息?是不是它假设是第一个验证从儿子和只有字符串?如果父亲试图从管道读取,并且儿子想写入管道,在这里的某个地方隐藏(我认为)是死锁,不是吗?为什么我没有陷入僵局?
由于
尽管Linux下的管道缓冲区是16kB,这对于保存一个48字节的消息应该足够了(所以在这个例子中应该确实是_never_block)。我认为这实际上只是一个调度/并发artefact。 – Damon 2012-07-16 12:14:39
@达蒙是的,这似乎很可能。 – trojanfoe 2012-07-16 12:15:34