gpt4 book ai didi

c - 如何管道不同的进程? (C)

转载 作者:行者123 更新时间:2023-11-30 16:09:50 26 4
gpt4 key购买 nike

我正在尝试通过管道传输两个不同的进程来实现终端的功能“|”。

我需要新的子进程本身执行命令,并 fork 另一个进程以使用第一个进程的输出执行不同的命令,然后在终端上输出最终进程的结果。

这是我的代码,我保持原始父级不变,因为之后我需要继续执行程序的其他部分。

int exec_pipe(char **args, int index, int *i, char**** jobs){

int fd1[2];
pid_t pid, wpid;
int status;
int savedStdOut = dup(1);
int savedStdIn = dup(fileno(stdin));

if (pipe(fd1)==-1)
{
fprintf(stderr, "Pipe Failed" );
return 1;
}

pid = fork();

if (pid < 0)
{
fprintf(stderr, "fork Failed" );
return 1;
}else if (pid == 0)
{
// Child process
close(fd1[0]);
dup2(fd1[1], 1);

printf("%s\n", args[index - 1]);

if (execvp(args[0], args) == -1)
{
printf("command not found\n");
}

int childId = fork();

if(childId < 0){
fprintf(stderr, "fork Failed" );
return 1;
}else if(childId == 0){
// child of child of parent

fdopen(fd1[1], "r");
dup2(fd1[1], savedStdOut);


if (execvp(args[index + 1], args) == -1)
{
printf("command not found\n");
}
exit(EXIT_FAILURE);

}else {
// parent of child of child of parent
do
{
wpid = waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status)); // wait for child until it's exited or been killed
fdopen(savedStdIn, "r");
close(fd1[0]);
close(fd1[1]);
}
}else{
// Parent process
do
{
wpid = waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status)); // wait for child until it's exited or been killed
}
return 1;

}

我收到以退出代码 9 结尾的程序的“没有此类文件或目录”错误。

最佳答案

根据一些评论解决了它,谢谢大家!

int fd1[2];
pid_t pid;

// allocate two pipe sets
if (pipe(fd1) < 0)
{
perror("Failed to create pipe.");
return EXIT_FAILURE;
}

// launch first child process.
if ((pid = fork()) < 0)
{
perror("Failed to fork child(1)");
return EXIT_FAILURE;
}

if (pid == 0)
{
// child
// stdout = fd1(write)
if(strcmp(args[0], args[index - 1]) == 0)
{
dup2(fd1[WRITE], STDOUT_FILENO);
close(fd1[READ]);
close(fd1[WRITE]);
execlp(args[0], args[0], (char*) NULL);
fprintf(stderr, "failed to execute '%s'\n", args[0]);
exit(1);
}else{
dup2(fd1[WRITE], STDOUT_FILENO);
close(fd1[READ]);
close(fd1[WRITE]);
execlp(args[0], args[0], args[index - 1], (char*) NULL);
fprintf(stderr, "failed to execute '%s'\n", args[0]);
exit(1);
}
}else
{
// parent
// fork once more.
if ((pid = fork()) < 0)
{
perror("Failed to fork child(2)");
return EXIT_FAILURE;
}

if (pid == 0)
{
// child of child
// stdin = fd1(read)
dup2(fd1[READ], STDIN_FILENO);
close(fd1[WRITE]);
close(fd1[READ]);
execlp(args[index + 1], args[index + 1], (char*) NULL);
fprintf(stderr, "failed to execute '%s'\n", args[index + 1]);
exit(1);
}else{
int status;
close(fd1[READ]);
close(fd1[WRITE]);
waitpid(pid, &status, 0);
}
}

关于c - 如何管道不同的进程? (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59010061/

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