【发布时间】:2023-03-13 00:00:01
【问题描述】:
如何使第二个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 重定向的内容。接下来会发生什么或我哪里出错了?
【问题讨论】:
-
这里是解释清楚的答案enter link description here
标签: c