我试图建立一个管道,以使用pipe()在子进程和父进程之间进行通信。我读了一些关于stackoverflow的帖子,其中一些使用dup()和dup2()函数。有人可以解释在这种情况下这些功能的用途吗?
您可以用来dup2
分别重定向子进程和父进程的stdin和stdout,以通过与指令创建的文件描述符一起使用的管道发送消息pipe
。为了更具体地说明其功能,下面是有关如何执行此操作的详细示例。
#include <unistd.h>
#include <stdio.h>
#define READ 0
#define WRITE 1
int main (int argc, char * argv [ ] )
{
int fd[2];
pipe(fd); // creating an unnamed pipe
if (fork() !=0)
{
close(fd[READ]); // Parent close the reading descriptor
dup2(fd[WRITE], 1); // copy fd[WRITE]] in the descriptor 1 (stdout)
close (fd[WRITE]); // closing the writing descriptor, not needed anymore because of stdout
if(execlp(argv[1], argv[1], NULL) ==-1) // execute the program writer passed as an argument to myprog
perror("error in execlp");
}
else // child process (reader)
{
// closing unused writing descriptor
close(fd[WRITE]);
// copy fd[READ] in descriptor 0 (stdin)
dup2(fd[READ],0);
close (fd[READ]); // closing reading descriptor, not needed anymore because of stdin
// execute reading command
if(execlp(argv[2], argv[2], NULL) == -1) // Execute the reader passed as an argument to myprog
perror("connect");
}
return 0 ;
}
这样,父进程通过标准输出发送的每个消息都将被重定向到子进程的标准输入。例如,执行命令myprog who wc
(使用上面显示的代码)时,其行为就像who | wc
在终端中一样。您可以看到我的父进程who
将wc
通过标准输出将消息发送到。
因为是dup
和之间的区别dup2
。您可以查看此链接。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句