[英]C: “write: Broken pipe” error
我想嘗試與子進程和父進程進行管道通信。 父進程寫入管道,而子進程讀取此,但我的程序得到錯誤“寫入:管道損壞”。 如何更改此代碼? 謝謝。
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <termios.h>
#include <errno.h>
#include <fcntl.h>
int main(void)
{
int i=0;
int child=5;
int fdp;
int fds[2];
int controlRead;
int controlWrite;
char pathName[30] = {"Trying Pipe Communication\n"};
if(pipe(fds) < 0)
{
perror("pipe");
exit(EXIT_FAILURE);
}
do{
if(child == 0)
{
close(fds[1]);
if( (controlRead = read(fds[0],pathName,sizeof(pathName)) ) <= 0)
{
perror("read");
exit(EXIT_FAILURE);
}
close(fds[0]);
printf("boru :%s\n",pathName);
wait();
}
else
{
printf("Parent process\n");
close(fds[0]);
if( (controlWrite = write(fds[1],&pathName,sizeof(pathName))) <= 0)
{
perror("write");
exit(EXIT_FAILURE);
}
close(fds[1]);
}
i++;
child = fork();
}while(i<3);
return 0;
}
錯誤“寫入:管道損壞”。 如何更改此代碼?
在寫之前不要破壞管道。 在第一次執行do / while循環時,父級關閉讀取端,然后將其寫入剩余的管道fd。 卡布蘭。 EPIPE。
您的讀取循環應計算關閉套接字之前讀取的字節數。 否則,終止時間過早。
管道不是數據包傳輸,並且單個讀/寫實際上是一系列操作。 因此,當您在編寫數組時,假設它會合而為一是錯誤的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.