简体   繁体   English

C:“写:管道损坏”错误

[英]C: “write: Broken pipe” error

I want to try Pipe communication with child and parent process. 我想尝试与子进程和父进程进行管道通信。 Parent process write to pipe and child process read this but my program get error "write: Broken pipe". 父进程写入管道,而子进程读取此,但我的程序得到错误“写入:管道损坏”。 How can I change this code? 如何更改此代码? Thnks. 谢谢。

#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;
}

error "write: Broken pipe". 错误“写入:管道损坏”。 How can I change this code? 如何更改此代码?

Don't break the pipe before you write to it. 在写之前不要破坏管道。 On the first pass through your do/while loop, the parent closes the read end and then writes to the remaining pipe fd. 在第一次执行do / while循环时,父级关闭读取端,然后将其写入剩余的管道fd。 Kablam. 卡布兰。 EPIPE. EPIPE。

Your read loop shall count number of bytes read before closing the socket. 您的读取循环应计算关闭套接字之前读取的字节数。 Otherwise it is terminated too early. 否则,终止时间过早。

Pipes are not packet transport, and single read/write is actually a series of operations. 管道不是数据包传输,并且单个读/写实际上是一系列操作。 So when you are writing an array, it is wrong to assume it will come in one piece. 因此,当您在编写数组时,假设它会合而为一是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM