我正在學習進程間通信,並且遇到了下面的示例程序。分叉和管道:這個C程序是否包含競態條件?
我不明白是爲了防止父進程與子進程之前嘗試的讀(如在程序底部的其他條件部分)已完成寫。
在子進程寫入標準輸出之前,什麼(如果有的話)限制父進程嘗試從標準輸入讀取數據?
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
exit(0);
}
else
{
/* 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("Received string: %s", readbuffer);
}
return(0);
}
當調用系統函數'pipe()'時,總是檢查返回值以確保操作成功。成功時,pipe()在失敗時返回0,pipe()返回-1並設置'errno' – user3629249
關於管道末端關閉的註釋向後 – user3629249
'read()'函數不會追加字符串終止符字節' \ 0'讀取字符串,所以立即調用printf()(可能)會失敗。根據首先發生的是read()還是write(),讀取可能會在沒有讀取所有數據字節的情況下返回。讀取應該在循環中,同時檢查/累積返回的字節數。當返回的字節數爲0時,使用累加的字節數終止字符串(可能不需要,因爲子節點發送終止字節,但這是一個很好的做法)如果返回的值<0,則處理錯誤 – user3629249