Search code examples
cunixpipeforkposix

How to using pipe in loop, is mine correct?


I want to know if my usage of pipe is correct, this code is in the fork() child process, and pfd is pipe pointer:

char buf[1024];
while(1){
    signal(SIGUSR1, OnSigUsr1);
    sleep(10000);
    if(get==1){
        get=0;
        close(pfd[1]);
        read(pfd[0], buf, sizeof(buf));
        close(pfd[0]);
    }
}

another episode of code in the parent code:

char buffer[1024];
/*put something in buffer*/
close(pfd[0]);
if(write(pfd[1], buffer, strlen(buffer))==-1){
     printf("error write\n");
};
close(pfd[1]);
kill(fpid,SIGUSR1);

My problem is the buffer can be written and get from fork() for only one time, next time it can't be written in pipe again and return error write. I wonder if I made it some place wrong. Thanks.


Solution

  • In the case of pipe, the write blocks if pipe is full.

    Note that the data written into the write-end of pipe is buffered in kernel until it is read from the read-end of the pipe.

    child : The pfd[1] can be closed in child as it is not used in child. But, it is not required to close pfd[0] if it shall be used by child subsequently.

    parent : Similarly, the pfd[0] can be closed in parent as it is not used in parent. But, it is not required to close pfd[1] if it shall be used by parent subsequently.