shen
shen

Reputation: 17

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.

Upvotes: 1

Views: 1381

Answers (2)

Karthik Balaguru
Karthik Balaguru

Reputation: 7852

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.

Upvotes: 0

JustinCB
JustinCB

Reputation: 523

You can only write data to an open file descriptor. The parent executes close(pfd[1]); after writing the buffer, and the child executes close(pfd[0]); after reading the buffer. Don't close a file descriptor if you will use it again, but close all open file descriptors before your program exits.

Upvotes: 1

Related Questions