1. Popen () function
Header files: #include <stdio.h>
Function prototype: FILE * popen (const char * command, const char * type);
Close the file stream: int pclose (file * stream);
The function Popen executes the fork first, then calls exec to execute cmd, and returns a standard I/O file pointer.
CMD is a string pointer containing a shell command (ending with a null end character);
If type is "R", then the file pointer is connected to the standard output of CMD;
If type is "W", then the file pointer is connected to the standard input of CMD.
2. Description
The 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 command parameter is a string pointer to a string that ends with a null terminator that contains a shell command. This command is sent to /bin/sh with the- C parameter, which is executed by the shell. The type parameter is also a pointer to a string ending with a null terminator, which must be ' r ' or ' W ' to indicate whether it is read or write.
The return value of the popen () function is a normal standard I/O stream that can only be closed with the pclose () function instead of the fclose () function.
Note that the output stream of the popen function is fully buffered by default; thepclose function waits for the associated process to end and returns the exit state of a command command, just like the wait4 function
3. Example
1#include <stdio.h>2 3 intMainvoid)4 {5FILE *FP;6 if(fp = Popen ("ls-l","r)) = = NULL)7 {8Perror ("Open failed!");9 return-1;Ten } One Charbut[ the]; A while(Fgets (But,255, fp)! =NULL) -printf"%s", buf); - if(Pclose (fp) = =-1) the { -Perror ("Close failed!"); - return-2; - } + return 0; -}
C-language popen function to implement shell and read content