如何将第二个execlp("sort","sort,",(char *)0)
输出到显示屏?
#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);
}
子级1具有execlps
系统调用,因此子级1执行ls程序。
dup2
将输出重定向到管道。
我认为孩子2 execlp
对ls进行排序,但代码只是挂起,我不确定我是否做得对,我期待孩子2显示孩子1重定向的内容。接下来会发生什么,或者我哪里出错?
答案 0 :(得分:1)
父进程和子进程2(sort)也打开了管道的写入结束,因此sort正在等待其stdin上的更多输入:close(c1Toc2[1]);
之前sleep(3);
和execlp("sort", "sort", (char *)0);
之前{{1}}必须添加{1}}。