Abstract: This article introduces the usage and behavior mechanism of the popen function, and provides examples to help illustrate how to use the popen function.
The file also describes several file operation functions, such as fopen, fread, and fwrite.
Author: zieckey (http://zieckey.cublog.cn)
All rights reserved!
Popen uses a FIFO pipeline to execute external programs.
# Include <stdio. h>
File * popen (const char * command, const char * type );
Int pclose (File * stream );
Popen
Determine the input/output direction of the command through whether the type is R or W. The R and W are relative to the command pipeline. R indicates that the command is read from the pipeline, W indicates
Command is output to its stdout through the pipeline, and popen returns the file stream pointer of the FIFO pipeline. Pclose is used to close the pointer after use.
The following is an example:
/*************************************** **************************************** ************
** Name: popen. c
** This program is used to show the usage of popen ().
** Author: zieckey, (zieckey@yahoo.com.cn)
** Date: 2007/9/30 :47
** All Rights Reserved!
**************************************** **************************************** ***********/
# 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, '/0', sizeof (BUF); // initialize the Buf to avoid gibberish in the file.
Stream = popen ("ls-L", "R"); // read the output of the "ls-L" command through the pipeline ("R" parameter) to file * stream
Wstream = fopen ("test_popen.txt", "W +"); // create a writable file
Fread (BUF, sizeof (char), sizeof (BUF), stream); // read the data stream of file * stream to Buf.
Fwrite (BUF, 1, sizeof (BUF), wstream); // write the data in the Buf to the stream corresponding to file * wstream, which is also written to the file
Pclose (Stream );
Fclose (wstream );
Return 0;
}
[Root @ localhost SRC] # GCC popen. c
[Root @ localhost SRC] #./A. Out
[Root @ localhost SRC] # Cat test_popen.txt
Total 128
-Rwxr-XR-x 1 Root 5558 09-30 a. Out
-Rwxr-XR-x 1 Root 542 09-30 child_fork.c
-Rwxr-XR-x 1 Root 480 09-30 execve. c
-Rwxr-XR-x 1 Root 1811 09-29 21:33 fork. c
-Rwxr-XR-x 1 Root 162 09-29 getpid. c
-Rwxr-XR-x 1 Root 1105 09-30 popen. c
-Rwxr-XR-x 1 Root 443 09-30 system. c
-Rwxr-XR-x 1 Root 0 09-30 :51 test_popen.txt
-Rwxr-XR-x 1 Root 4094 09-30 test.txt