The popen function allows a program to invoke another program as a new process and either pass data to it or receive data from it. The command string is the name of the program to run, together with any parameters. open_mode must be either “r” or “w”.
If the open_mode is “r”, output from the invoked program is made available to the invoking program and can be read from the file stream FILE * returned by popen, using the usual stdio library functions for reading (for example, fread). However, if open_mode is “w”, the program can send data to the invoked command with calls to fwrite. The invoked program can then read the data on its standard input. Normally, the program being invoked won’t be aware that it’s reading data from another process; it simply reads its standard input stream and acts on it.
A call to popen must specify either “r” or “w”; no other option is supported in a standard implementation of popen. This means that you can‘t invoke another program and both read from and write to it. On failure, popen returns a null pointer. If you want bidirectional communication using pipes, the normal solution is to use two pipes, one for data flow in each direction. pclose When the process started with popen has finished, you can close the file stream associated with it using pclose. The pclose call will return only when the process started with popen finishes. If it’s still running when pclose is called, the pclose call will wait for the process to finish. The pclose call normally returns the exit code of the process whose file stream it is closing. If the invoking process has already executed a wait statement before calling pclose, the exit status will be lost because the invoked process has finished and pclose will return –1, with errno set to ECHILD.
(翻译自linux程序设计第四版13章)
Popen函数让一个程序可以调用另一个函数成为一个新进程,从而传递数据或者接收数据。命令行就是将要执行的程序的名字,可以带任何参数,打开方式必须是只读或只写的一种。
如果打开方式是只读,调用程序可以通过popen返回的文件流File*获得被调用函数的输出,这将用到标准输入输出函数库stdio,比如fread。另外,如果打开方式是只写,那么调用程序可以通过使用fwrite函数将数据传送给被调用函数。被调用程序就可以从它的标准输入输出读取数据。一般的,被调用程序不会(意识到?)它正在从另一个进程读取数据。它单纯的读取基本输入流并执行它。
Popen的调用必须指定只读或只写;在popen的实现中不支持其他选项。这就意味着你不能通过读写的方式调用另一个程序。如果你想双向通信,一般的解决办法就是使用两个管道,每个管道对应一个方向的数据流。当popen结束时,你可以使用pclose关闭与之有关的文件流。Pclose 调用只会在调用popen的进程结束的时候返回。如调用pclose的时候它还在运行那么pclose将等待。Pclose调用关闭文件流的进程的退出码。如果调用进程在调用pclose之前执行了wait语句,退出状态将会丢失应为调用进程已经结束,pclose将返回-1,errno设置为ECHILD。