我想通过在c中使用execvp来执行一个linux命令,它并没有显示任何东西。我不太明白dup2()函数调用。任何人都可以告诉我我在这里做错了什么?当在c中使用系统调用来管道命令时,输出不显示任何内容?
命令执行:ls |排序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdbool.h>
int main()
{
char *cmd[2], *cmd2[3];
cmd[0] = "ls";
cmd[1] = NULL;
cmd2[0] = "sort";
cmd2[1] = NULL;
pid_t id;
id = fork();
int pipe1[2];
int pipe2[2];
pipe(pipe1);
pipe(pipe2);
if(id==0)
{
printf("child process with pid =%d \r\n", getpid());
//the read end of pipe not needed,
close(pipe1[0]);
// we want the stdout (1) of this process to be connected to 1 of pipe1.
dup2(pipe1[1],1); //or dups(pipe1[1], stdout_fileno)
//close it aswell not needed
//close(pipe1[1]);
execvp("ls",cmd);
return 1;
}
pid_t id2 = fork();
if(id2==0)
{
close(pipe1[1]);
dup2(pipe1[0], 0);
close(pipe1[0]);
execvp("sort",cmd2);
//return 1;
}
close(pipe1[0]);
close(pipe1[1]);
waitpid(id,NULL,0);
waitpid(id2, NULL, 0);
//execvp("sort",cmd2);
//printf("parent process with pid =%d \r\n", getpid());
return 0;
}
如果你想让管道连接父和子,你需要在你的fork()之前'pipe()'*。 – EOF