2016-06-09 43 views
0

我想通过在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; 
} 
+1

如果你想让管道连接父和子,你需要在你的fork()之前'pipe()'*。 – EOF

回答

1

你只需要一个管道,而实际上只使用一个,即使你创建两个。除了你实际创建四个,因为你在第一个fork()之后创建管道,因此父进程和第一个子进程分别创建两个。

而这似乎是问题所在。如果您希望两个子进程通过管道进行通信,则他们必须使用相同的管道。他们通过从父进程继承管端的打开文件描述符来实现这一点,这需要他们使用一个进程创建的管道,这个进程同时下降(即父进程)和在子进程之前创建的进程。就目前来看,只有第二个孩子这样做;第一种是使用自己创建的管道,因此它不与其他任何东西连接。

+0

OMG ,,,我很蠢......谢谢alott john –

相关问题