c - regarding the relation of close() and read() -
int main() { char *msg="hello"; char buff[max]; int p[2]; pipe(p); int i,pid=fork(); if(pid>0){ //close(p[1]); read(p[0],buff, max); } else { printf("child exiting\n"); } }
why above code end blocking ? if remove comment , place
close(p[1])
then why code end ?
once create pipe, gets 4 ends:
- a reading end
p[0]
in parent process - a writing end
p[1]
in parent process - a reading end
p[0]
in child process - a writing end
p[1]
in child process
unix not deliver eof
reader unless both writing ends have been closed, because knows pipe still writeable.
when child process exits, closes both ends of pipe on side. however, parent still has 1 writeable end open, reading pipe blocks instead of delivering eof
parent. why unix manual instructs close unused ends of pipe right away:
an application uses
pipe(2)
,fork(2)
should use suitableclose(2)
calls close unnecessary duplicate file descriptors; ensures end-of-file ,sigpipe
/epipe
delivered when appropriate.
here example of how make program not block without closing p[1]
on parent side:
#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <pthread.h> void* write_pipe(void* pp) { int* p = (int*)pp; char msg[] = "hello thread!"; write(p[1], msg, sizeof(msg)); return null; } int main() { char buff[100]; int p[2]; pipe(p); int pid=fork(); if(pid>0){ pthread_t thread1; pthread_create (&thread1, null, &write_pipe, (void *)p); read(p[0],buff, 100); printf("%s\n", buff); printf("parent exiting\n"); } else { printf("child exiting\n"); } return 0; }
the code above writes writing end of pipe thread within parent process, instead of writing child process. legitimate use of pipe, too, illustrating why unix cannot deliver eof
unless parent's writing end of pipe closed.
Comments
Post a Comment