gpt4 book ai didi

c - 如何使用execlp()?

转载 作者:太空宇宙 更新时间:2023-11-03 23:47:44 26 4
gpt4 key购买 nike

如何使第二个 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);
}

child 1 有 execlps 系统调用,所以 child 1 执行 ls 程序。dup2 将输出重定向到管道。我认为 child 2 execlp 对 ls 进行排序,但代码只是挂起,我不确定我是否做对了,我希望 child 2 显示 child 1 重定向的内容。接下来会发生什么或我哪里出错了?

最佳答案

父进程和子进程 2(sort)也打开了管道的写入端,因此 sort 正在等待其标准输入的更多输入:a close(c1Toc2[1]);之前 sleep(3);和之前 execlp("sort", "sort", (char *)0);必须添加。

关于c - 如何使用execlp()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28918270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com