shen shen - 1 year ago 90
C Question

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];
signal(SIGUSR1, OnSigUsr1);
read(pfd[0], buf, sizeof(buf));

another episode of code in the parent code:

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

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download