Reputation: 21
How to do I make the second execlp("sort","sort,",(char *)0)
output to the display?
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "errno.h"
int main()
{
int parprocID = getppid();//parent process id
int c1Toc2[2];
int c2Toc1[2];
pipe(c1Toc2);//pipe 1, to child 2
pipe(c2Toc1);//pipe 2, to child 1
int cpid = 0;//child 1 pid
int cpid2 = 0;//child 2 pid
int child1,child2;//Child variable
printf("Parent Process id is: %d.\n\n", parprocID);//parent pid introduction.
child1 = fork();//creation of child 1
if(child1 == 0)
{
cpid = getpid();
printf("Child 1 created by process: %d has an id of %d.\n\n", parprocID, getpid());
dup2(c1Toc2[1], STDOUT_FILENO);//redirect from stdout to pipe
execlp("ls", "ls","-al","/bin", (char *)0);
exit(0);
}
else
{
child2=fork(); //creation of child 2
if(child2 == 0)
{
cpid2 = getpid();
printf("Child 2 created by process: %d has an id of %d.\n", parprocID, getpid());
dup2(c1Toc2[0], STDIN_FILENO);
execlp("sort", "sort", (char *)0);
exit(0);
close(c1Toc2[0]);
close(c1Toc2[1]);
}
}
sleep(3);
printf("PARENT: PROCESS waiting on children to complete\n");
wait(NULL);
wait(NULL);
printf("Final print statement before exit\n");
exit(0);
}
Child 1 has the execlps
system call so the child 1 executes the ls program.
dup2
redirects the output to the pipe.
I think child 2 execlp
sorts the ls but the code just hangs, I'm not sure if I'm doing it right, I'm expecting the child 2 to display what child 1 redirected. What comes next or where am I going wrong?
Upvotes: 2
Views: 603
Reputation: 2499
The parent process and the child process 2 (sort) have open the writing end of the pipe too, thus sort is waiting for more input on its stdin: a close(c1Toc2[1]);
before sleep(3);
and before execlp("sort", "sort", (char *)0);
must be added.
Upvotes: 1