c - Fork and dup2 - Child process is not terminating - Issues with file descriptors? -
i writing own shell homework assignment, , running issues.
my shell programme gets input cat scores | grep 100
console and prints output expected grep
command doesn't terminate , can see running infinitely ps
command.
edit - there error while closing fds. grep command not executing , console output -
grep: (standard input): bad file descriptor
i reading number of commands console , creating necessary pipes , storing them in 2 dimensional int array fd[][]
before forking first process.
fd[0][0]
contain read end of 1st pipe , fd[0][1]
contain write end of 1st pipe. fd[1][0]
contain read end of 2nd pipe , fd[1][1]
contain write end of 2nd pipe , on.
each new process duplicates stdin
read end of pipe previous process , duplicates stdout
write end of pipe next process.
below function:
void run_cmds(char **args, int count,int pos) { int pid,status; pid = fork(); if ( pid == 0 ) { if(pos != 0) dup2(fd[pos-1][0],0); // not changing stdin 1st process if(pos != count) dup2(fd[pos][1],1); //not changing stdout lastly process close_fds(pos); execvp(*args,args); } else { waitpid(pid,&status,0); count--; pos++; //getting next command , storing in args if(count > 0) run_cmds(args,count,pos); } } }
args contain arguments command. count number of commands need create. pos position of command in input i not able figure out problem. used same approach hard coded values before , working.
what missing understanding/implementation of dup2
/fork
, why command waiting infinitely?
any inputs helpful. struck past couple of days!
edit : close_fds() function below - process , closing both pipes linking process.
void close_fds(int pos) { if ( pos != 0 ) { close(fd[pos-1][0]); close(fd[pos-1][1]); } if ( pos != count) { close(fd[pos][0]); close(fd[pos][1]); } }
most probable reasons why grep
doesn't terminate:
you don't phone call waitpid
proper pid (even though there such phone call in code, may not executed reason), grep
becomes zombie process. maybe parent shell process waiting process first (infinitely, because other 1 never terminates), , doesn't phone call waitpid
pid of grep
. can find z
in output of ps
if grep
zombie.
grep
doesn't receive eof on stdin (fd 0), process keeping write end of pipe open. have closed file descriptors in fd
array in parent shell process? if not closed everywhere, grep
never receive eof, , never terminate, because blocked (forever) waiting more info on stdin.
c linux fork dup2
No comments:
Post a Comment