gpt4 book ai didi

c - C 中的匿名管道与 execlp

转载 作者:行者123 更新时间:2023-11-30 17:36:10 25 4
gpt4 key购买 nike

我的大学有一项作业,其中必须有一个主进程和 3 个子进程。我必须从用户那里读取主进程中的表达式,然后通过 p1 进程中的匿名管道传递它并重定向标准输入。然后我必须修改它并用另一个管道将其传递到 p2。然后 p3 和另一个管道也会发生同样的事情。最后我必须使用另一个管道将最终表达式从 p3 返回到主进程。当我通过调用fork在主进程中创建p1,p2,p3进程时,我使用execlp来运行每个进程的代码。

到目前为止我所做的(除了每个进程的逻辑非常复杂),是将用户的表达从主进程发送到 p1 进程。在主进程中 p1 的代码中,我将 p1 的输入重定向到第一个管道的读取端,并且成功地从主进程中读取了表达式。

我的问题出在其他进程上。我真的很困惑如何正确重定向每个管道的输入和输出以与所有进程进行通信。我真的很感激这里的任何帮助。预先感谢您。

最佳答案

在此示例中,您可以看到 execlp() 函数和 fork() 函数:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main()
{
pid_t pid;
char *pathvar;
char newpath[1000];

pathvar = getenv("PATH");
strcpy(newpath, pathvar);
strcat(newpath, ":u/userid/bin");
setenv("PATH", newpath);

if ((pid = fork()) == -1)
perror("fork error");
else if (pid == 0) {
execlp("newShell", "newShell", NULL);
printf("Return not expected. Must be an execlp error.n");
}
}

在这里您可以看到如何在两个进程之间建立管道:

/*
“ls -R | grep <pat>” where <pat> is a pattern
*/

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv [])
{
int pipe1[2];
int pid1;
int pid2;
char stringa[100];

pipe(pipe1); // creo la pipe

if((pid1=fork())==0)
{
close(pipe1[0]);
dup2(pipe1[1],1);
close(pipe1[1]);
execlp("ls","ls","-R",NULL);
}

if((pid2=fork())==0)
{
close(pipe1[1]);
dup2(pipe1[0],0);
close(pipe1[0]);
execlp("grep","grep",argv[1],NULL);
}

close(pipe1[0]);
close(pipe1[1]);
waitpid(pid1,NULL,0);
waitpid(pid2,NULL,0);
exit(0);

}

关于c - C 中的匿名管道与 execlp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22783418/

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