2014-02-27 126 views
0

嗨,有人可以解释为什么我应该关闭我的管道后使用execlp?为什么我关闭管道后关闭execlp?

下面是一个例子:

if(cid == 0) 
{//Only child cid can run this code 

    char msg[256]; 

    //Redirect output into the pipe instead of the terminal 
    dup2(pipe1Fds[1],STDOUT_FILENO); 

    //Close pipes or the pipe reader will not get an EOF 
    close(pipe1Fds[0]); 
    close(pipe1Fds[1]); 
    close(pipe2Fds[0]); 
    close(pipe2Fds[1]); 

    //Execute cmd1 
    execlp(cmd1,cmd1,(char *)0); 

    exit(0); 
} 
+0

阅读[高级Linux编程](http://advancedlinuxprogramming.com/) –

回答

1

execlp()会将不同的代码加载到此进程中,然后运行新程序,因此您需要在加载目标代码之前关闭管道,因为目标代码不会访问管道。
你可以阅读以获取更多信息link。由于您的代码将被execlp()加载的程序替换,所以您必须在调用execlp()之前关闭管道。

1

你有dup2倒是管FD到STDOUT FD,所以你不需要它了,需要关闭它(所以它对于一个EOF读者)。

execlp(如果它有输出)执行的程序认为它向STDOUT写入,但STDOUT FD已更改为管道FD,所以其写入管道FD。

+0

'execlp'只是执行一个程序。它不写任何东西。 –

+0

@BasileStarynkevitch肯定 - 但该程序的执行可能会写入STDOUT,该STDOUT已被复制到管道FD。我已经编辑来澄清我的陈述。 –