c - Behavior of program changes depending on where fork is called -
i working on little program getting familliar pipes , file descriptors , spent lot of time debugging problem not make sense.
i spent ton of time thinking misunderstood file descriptors when program behaving differently depending on used fork.
int main(void) { int fid; int p[2]; pipe(p); char buf[20]; fid = fork(); if (fid==0){ close(p[1]); dup2(p[0],0); close(p[0]); execlp("cat","cat",(char *)null); } else{ close(p[0]); dup2(p[1],1); close(p[1]); execlp("ls","ls",(char *)null); } return 0; }
gives me expected output of whats in directory. ls out put gets piped cat.
if move fork line above pipe(p); wont output. don't understand why happens?
so you're wondering why works:
pipe(p); fid = fork();
and doesn't:
fid = fork(); pipe(p);
the reason pretty straightforward: in first case, process creates pipe, splits 2 (and both processes have access pipe).
in second case, process splits two, , each of 2 processes creates own pipe that's unrelated other one.
so in first case, 1 process writes pipe , other process reads it. in second case, 1 process writes pipe , other process reads a different pipe, hasn't received data because it's different pipe.
Comments
Post a Comment