c - Pipe and Process managment -



c - Pipe and Process managment -

i working on tiny shell(tsh) implemented in c(it's assignment). 1 part of assignment belongs piping. have pipe command's output command. e.g:ls -l | sort

when run shell, every command execute on it, processed kid process spawns. after kid finishes result returned. piping wanted implement harcoded illustration first check how works. wrote method, partially works. problems when run pipe command, after kid process finishes, whole programme quits it! not handling kid process signal properly(method code below).

my question:

how process management pipe() works? if run command ls -l | sort create kid process ls -l , process sort ? piping examples have seen far, 1 process created(fork()).

when sec command (sort our example) processed, how can process id?

edit: while running code result twice. don't know why runs twice, there no loop in there.

here code:

pid_t pipeit(void){ pid_t pid; int pipefd[2]; if(pipe(pipefd)){ unix_error("pipe"); homecoming -1; } if((pid = fork()) <0){ unix_error("fork"); homecoming -1; } if(pid == 0){ close(pipefd[0]); dup2(pipefd[1],1); close(pipefd[1]); if(execl("/bin/ls", "ls", (char *)null) < 0){ unix_error("/bin/ls"); homecoming -1; }// end of if command wasn't successful }// end of pid == 0 else{ close(pipefd[1]); dup2(pipefd[0],0); close(pipefd[0]); if(execl("/usr/bin/tr", "tr", "e", "f", (char *)null) < 0){ unix_error("/usr/bin/tr"); homecoming -1; } } homecoming pid; }// end of pipeit

yes, shell must fork exec each subprocess. remember when phone call 1 of execve() family of functions, replaces current process image exec'ed one. shell cannot go on process farther commands if straight execs subprocess, because thereafter no longer exists (except subprocess).

to prepare it, fork() 1 time again in pid == 0 branch, , exec ls command in child. remember wait() both (all) kid processes if don't mean pipeline executed asynchronously.

c shell pipe waitpid

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -