gpt4 book ai didi

C 通过管道连接到另一个程序的 STDIN 并执行

转载 作者:行者123 更新时间:2023-11-30 14:53:09 25 4
gpt4 key购买 nike

我不明白为什么execl-command中的程序没有从父进程获取输入:

我的代码:(我删除了错误处理和其他一些步骤以使其更简单)

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

int main(int argc, char *argv[]){
int pipefd[2];
pipe(pipefd);
pid_t pid = fork();
switch(pid){
case -1:
exit(EXIT_FAILURE);
case 0:
close(pipefd[1]);
dup2(pipefd[0], STDIN_FILENO);
close(pipefd[0]);
execl("/usr/bin/wc", "-w", NULL);
fflush(stdout);
exit(EXIT_SUCCESS);
default:
close(pipefd[0]);
FILE *pipewrite = fdopen(pipefd[1], "w");
char *ar[] = {"W1", "W2", "W3", "W4", "W5"};
for(int i = 0; i < 5; i++){
fputs(ar[i], pipewrite);
fflush(pipewrite);
}
fflush(pipewrite);
fclose(pipewrite);
}
exit(EXIT_SUCCESS);
}

如果我启动程序,输出应该是 5。

最佳答案

execl 调用有问题。

这个

execl("/usr/bin/wc", "-w", NULL);

需要:

execl("/usr/bin/wc", "wc", "-w", NULL);

也就是说,您还需要将命令 (wc) 作为参数传递给 execl

您将看到的下一个问题是 wc 没有 5。这是因为您从父进程传递的所有标准输入内容都被视为单个单词(由于缺少空格)。基本上,如果你这样做:

   fputs(ar[i], stdout);

在父进程中,stdout 上看到的内容就是子进程看到的内容。

以某种方式添加空格。例如,您可以再次调用fputs:

   fputs(ar[i], pipewrite);
fputs(" ", pipewrite);

或者,您可以在字符串中包含空格:

char *ar[] = {"W1 ", "W2 ", "W3 ", "W4 ", "W5"};

关于C 通过管道连接到另一个程序的 STDIN 并执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47371375/

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