[英]Can't read and print pipe content (from child executing through execv)
我编写了一个程序,它读取 bash 文件并执行该文件中的命令。 我得到了执行部分的工作,但我似乎无法将命令 output 重定向到 pipe,然后从 pipe 读取并打印其内容。 我已经阅读了有关该主题的一些主题,但解决方案似乎不起作用。 这是代码,
int main(int argc, char * argv[]) {
int pipefd[2];
char buf[1024];
int bytes = 0;
for (int i = 1; i < argc; i++) { // reading file as argument one at a time
FILE * fp;
fp = fopen(argv[i], "r");
char * buffer = NULL;
size_t buf_size = 0;
char bufread[1024];
int bytes_read = 0;
while (getline( & buffer, &buf_size, fp) != EOF) {
pid_t pid;
pid = fork();
pipe(pipefd);
if (pid == 0) {
close(pipefd[0]);
dup2(pipefd[1], 1);
dup2(pipefd[1], 2);
close(pfd[1]);
int length = countWords(buffer);
char * init_argv[length + 2];
init_argv[0] = "sh";
init_argv[1] = "-c";
init_argv[2] = buffer;
init_argv[3] = NULL;
execv("/bin/bash", init_argv);
} else {
int status;
close(pfd[1]);
waitpid(pid, & status, 0);
while (read(pfd[0], bufread, sizeof(bufread)) != 0) {
fprintf(stdout, "%s\n", bufread);
}
}
}
}
}
return 0;
}
当这个程序使用包含命令作为参数的有效文件运行时,为什么没有任何 output? 我知道没有 dup2 和 close 指令,程序会执行命令,所以这不是问题。 一旦我将 dup2 和 close 指令添加到程序中,我就无法再调试它(它在 execv 处崩溃)。
我不确定这是否是问题,但不应该调用pipe(pipefd);
在调用fork
之前执行?
就像现在一样,我认为父母和孩子各自创建了一个不同的 pipe,如果这是你想做的,他们不能使用这些管道相互通信。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.