c - Child Fork Process using fork() and pipe() -
i have create pipe creates 2 child processes fork(). child 1 redirects stdout write end of pipe , executes execlp() "ls -al" command. child 2 redirects input stdin read end of pipe, executes "sort -n -k 5" command. after creating both children, parent process waits them terminate before can exit. when run code, gives following output:
pipes pipes.c pipes.c~
the parent program same thing shell runs command "ls -al | sort -r -n -k 5". when command line, following:
-rwxrwxr-x 1 username username 8910 may 28 21:52 pipes drwxrwxr-x 3 username username 4096 may 28 13:52 .. drwxrwxr-x 2 username username 4096 may 28 21:52 . -rwxrwxr-x 1 username username 1186 may 28 21:52 pipes.c -rwxrwxr-x 1 username username 1186 may 28 19:48 pipes.c~
is there im not doing correctly in code output? tips?
my code:
#include <stdio.h> #include <string.h> // strlen #include <stdlib.h> // exit #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> int main() { int pipes[2]; pid_t child1, child2; //pipe int p = pipe(pipes); if (p<0){ //pipe fails fprintf(stderr, "pipe fail"); exit(2); } //child2 process child2 = fork(); //creating child2 if(child2 < 0){//fork fail fprintf(stderr, "child2 fork failed\n\n"); exit(3); }else if(child2 > 0){ //parent //child1 process child1 = fork(); //creating child1 if(child1 <0){//fork fail fprintf(stderr, "child1 fork failed\n\n"); exit(4); }else if(child1 ==0){//child1 p dup2(pipes[1], 1); close(pipes[0]); execlp("ls","-al",null); } wait(null);//parent waits } else if(child2 ==0){ //child2 dup2(pipes[0],0); close(pipes[1]); execlp("sort", "-r", "-n", "-k" , "5", null); } return 0; }
exec
, friends expect provide arguments new program's argv
vector. remember convention, argv[0]
name of program, , command-line arguments begin @ argv[1]
.
but not providing argv[0]
argument, example ls
thinks called through symbolic link named -al
, not given arguments.
the right way is
execlp("ls", "ls", "-al", null);
Comments
Post a Comment