Reprint http://www.cnblogs.com/caosiyang/archive/2012/06/25/2560976.html
Simply say the Popen () function
function definition
1 #include <stdio.h>23 FILE * Popen (constcharconst Char *type); 4 int pclose (FILE *stream);
function Description
The Popen () function creates a child process by creating a pipe, calling fork (), and executes a shell to run the command to open a process. This pipe must be closed by the Pclose () function instead of the fclose () function. The Pclose () function closes the standard I/O stream, waits for the command execution to end, and then returns the Shell's terminating state. If the shell cannot be executed, the terminating state returned by Pclose () is the same as the shell has executed exit.
The type parameter can only be read or write, and the resulting return value (standard I/O stream) also has a read-only or write-only type corresponding to type. If type is "R" then the file pointer is connected to the standard output of command, and if type is "W" then the file pointer is connected to the standard input of command.
The command parameter is a pointer to a null-terminated shell command string. This line of command will be passed to bin/sh and use the-c flag and the shell will execute the command.
The return value of Popen () is a standard I/O stream that must be terminated by Pclose. As mentioned earlier, this flow is unidirectional (can only be used for reading or writing). Writing to this stream is equivalent to writing the standard input to the command, the standard output of the command is the same as the process of calling Popen (), and, conversely, reading the data from the stream is equivalent to reading the standard output of the command, the standard input of the command and the process of calling Popen ().
return value
If the call to fork () or pipe () fails, or if memory cannot be allocated, it returns NULL, otherwise the standard I/O stream is returned. Popen () did not set errno value for memory allocation failure. If an error occurs when the fork () or pipe () is called, errno is set to the appropriate error type. If the type parameter is not valid, errno will return einval.
Attach an example:
1 //Execute shell Command2 //executes a shell command, the output is stored line by row in Resvec, and the number of rows is returned3int32_t Myexec (Const Char*cmd, vector<string> &Resvec) {4 resvec.clear ();5FILE *pp = Popen (cmd,"R");//Build Pipelines6 if(!PP) {7 return-1;8 }9 Chartmp[1024x768];//set an appropriate length to store each line of outputTen while(Fgets (TMP,sizeof(TMP), pp)! =NULL) { One if(Tmp[strlen (TMP)-1] =='\ n') { ATmp[strlen (TMP)-1] =' /';//Remove line break - } - Resvec.push_back (TMP); the } -Pclose (PP);//Close Pipe - returnresvec.size (); - }