Description: This paper introduces the use and behavior mechanism of popen function, and gives practical examples to illustrate the use of popen function. The Popen function executes an external program using a FIFO pipeline, first let's look at the function prototype of Popen: #include <stdio.h>file *popen (const char *command, const char *type); int Pclose (FILE *stream); popen determines the input/output direction of the command by Type R or W, and R and W are relative command pipes. R means the command is read in from the pipe, and W means that the command is output by the pipeline to its stdout,popen to return a file stream pointer to the FIFO pipeline. The pclose is used to close the pointer after the end of use. Let's look at an example:/********************************************************************************************* Name: popen.c** this program was used to show the usage of Popen (). ***************************************** /#include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h>int main (void) { file *stream; file *wstream; char buf[1024]; memset (buf, ' buf ', sizeof);//initialize BUF to avoid writing as garbled to file stream = Popen ("Ls-l", "R"); The output of the "ls-l" command is read through the pipe ("r" parameter) to file* stream Wstream = fopen ("Test_popen.txt", "w+"); Create a new writable file fread (buf, sizeof (char), sizeof (BUF), stream); Read the data stream just file* stream into buf fwrite (buf, 1, sizeof (BUF), wstream),//writes data from buf to file * Wstream corresponds to the stream, also written to the file Pclose (stream); fclose (wstream); return 0;} [[email protected] src]# gcc popen.c [[email protected] src]#./a.out [[email Protected] src]# cat test_popen.txt total 128-rwxr-xr-x 1 root root 5558 09-30 11:51 a.out-rwxr-xr-x 1 root root 542 09- 00:00 child_fork.c-rwxr-xr-x 1 root root 480 09-30 00:13 execve.c-rwxr-xr-x 1 root root 1811 09-29 21:33 FORK.C-RWXR-XR -X 1 root root 162 09-29 18:54 getpid.c-rwxr-xr-x 1 root root 1105 09-30 11:49 popen.c-rwxr-xr-x 1 root root 443 09-30 00:55 system.c-rwxr-xr-x 1 root root 0 09-30 11:51 test_popen.txt-rwxr-xr-x 1 root root 4094 09-30 11:39 te St.txt
Popen functions called by C and Shell under Linux