我想尝试与子进程和父进程进行管道通信。父进程写入管道,子进程读取此内容,但我的程序出现错误“写入:管道损坏”。如何更改此代码?谢谢。
#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;
}