鑑於這種代碼:在父子之間發送消息 - 爲什麼沒有死鎖?
#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