Preface
When we want to call an existing program in C language and want to get the program return value instead of outputting it in the terminal, we must call itpopen( )
The function is here.
popen( )
A pipeline is created and a new process is started, through which inter-process communication is conducted.popen( )
Returns a file pointer, similarfopen( )
, but the file pointer is not used to read or write to the input/output of the child process.
popen( )
There are two modes for functions: read moder
and write modew
. In read mode, data is read from the output of the child process; in write mode, data is written to the input of the child process.
1. popen( ) function prototype
popen( )
In the standard library<>
Function prototype in:man documentation
#include <> FILE *popen(const char *command, const char *type); int pclose(FILE *stream);
File pointers need to be recycled,pclose( )
Function.
2. Usage examples (provided by AI)
The following code can be used in both Linux and Windows,ls -l
It is a Linux command used to display the contents of the specified working directory (list the files and subdirectories contained in the current working directory).
#include <> int main() { FILE *fp; char buffer[1024]; // Execute the command and read the output fp = popen("ls -l", "r"); if (fp == NULL) { printf("Cannot execute command\n"); return 1; } // Read the output and print it while (fgets(buffer, sizeof(buffer), fp) != NULL) { printf("%s", buffer); } // Close the file pointer pclose(fp); return 0; }
Summarize
I used it in an articlepopen( )
Function Callwmic cpu get
Commands, and output them into the program to interpret the computer's cpu properties.
Although the C language textbook will not introduce this standard library function, since it is so useful, I will master it.
The above is the detailed content of the return value of other processes when calling popen( ) function in C language. For more information about popen( ) function in C language, please pay attention to my other related articles!