The standard I/O Library provides two functions, popen and pclose , whose function is to create a pipeline that connects to another process. It then reads its output or sends data to its input. Fork a subprocess first to close the unused pipe end.
Popen () function starts a process by creating a pipeline and invokes the shell . because pipelines are defined as unidirectional, the type parameter can only be defined as read-only or write-only, not both, and the resulting stream is read-only or write -only .
the prototype of the function popen :
file* POPEN (const char* cmdstring,const char* type)
If successful, returns the file pointer, and returns NULL if an error occurs
the function Popen first executes the Fork, and then calls exec to execute the cmdstring. and returns a file pointer if the type is "R ", the file pointer is connected to The standard output of the cmdstring, if the type is "w ", the file pointer is connected to The standard input of the cmdstring.
Here is a test case, simply use this function:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main ()
{
FILE *stream;
FILE *wstream;
Char buf[1024];
memset (buf, ' n ', sizeof (BUF));
Stream=popen ("Ls-l", "R");// will be " ls-a " commands are read through the pipe ( " R " ) to stream
Wstream=fopen ("Myopen.txt", "w+");// Create a new writable file
Fread (Buf,sizeof (char), sizeof (BUF), stream),/ / reads the data stream from the stream to the buf
Fwrite (Buf,sizeof (char), sizeof (BUF), wstream);/ /writes buf data to wstream
Fclose (Wstream);
Pclose (stream);
return 0;
}
Operation Result:
650) this.width=650; "title=" Picture 1.png "alt=" Wkiol1cm-lxxentqaabfhvqnfnw131.png "src=" http://s2.51cto.com/wyfs02/M01 /7e/eb/wkiol1cm-lxxentqaabfhvqnfnw131.png "/>
The usage of Popen function and the matters needing attention