Linux popen()函数内部实现原理
最近发现了一个函数 popen()/pclose() ,所以现在打算理清下思路…
正文
linux下的 popen 函数,大概就是通过 fork 一个子进程来执行命令并返回执行的结果给父进程.
The popen() function shall execute the command specified by the string command. It shall create a pipe between the calling program and the executed command, and shall return a pointer to a stream that can be used to either read from or write to the pipe.
http://pubs.opengroup.org/onlinepubs/009695399/functions/popen.html
函数声明如下
1 |
|
当然了,更重要的是要知道该函数内部是怎么实现的,大概步骤如下:(此处仅讨论子进程返回结果给父进程!)
- 父进程通过 pipe() 创建 读/写匿名管道 ,并关闭写管道pfd[1]
- 然后 fork() 创建子进程
- 子进程 close() 读管道pfd[0]和标准输出(STDOUT_FILENO=1) ,并 dup() 写管道pfd[1]
- 子进程通过 execl() 执行命令,执行的结果为标准输出重定向到了写管道pfd[1]
- 父进程 wait() 子进程退出,接着 fdopen() 通过文件描述符返回一个 FILE* . 注意返回文件指针时,不能关闭读管道pfd[0],可以通过后续 fclose() 关闭该描述符
- fclose() 关闭该读管道pfd[0]
简单实现代码如下:
1 |
|
1 |
|
其中,较重要的是在子进程中重定向标准输出,这里给出其他方法重定向标准输出到管道描述符
1 |
|
结尾
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!