I. Introduction to Functions
1.1Function prototype:
# Include <stdio. h>File* Popen (Const Char* Command,Const Char* Open_mode );
1.2Description
Popen Function allowsProgramStart another program as a new process and pass data to it or receive data through it. Command The string is the name of the program to be run and the corresponding parameters (for example: Ls Or Ls-l ), Openmode Required R Or W . If yes R The output of the called program can be used by the program that calls it. W To call the program. Fwrite Send data to the called program as its input in the standard input stream.
2. Test Program preparation
Prepare two simple programs for the test below.
2.1Output Test Program
View code
//Outputtest. c# Include <stdio. h>IntMain () {printf ("Just a test! \ N");Return 0;}
The main function is to output a string to the standard output device for the following program to test.
2.2Input test program
View code
//Inputtest. c# Include <stdio. h>IntMain (){CharBuf [1024] = {0}; Scanf ("% S", Buf); printf ("Your input: % s \ n", Buf );Return 0;}
It is mainly used to input and output strings from the standard input device for testing in the following program.
III,PopenOperation example (CCode)
3.1Obtain program output
ToOutputtestThe Code is as follows:
View code
# Include <unistd. h> # Include <Stdlib. h> # Include <Stdio. h># Include < String . H> Int Main () {File * Read_fp; Char Buffer [bufsiz + 1 ]; Int Chars_read; memset (buffer, ' \ 0 ' , Sizeof (Buffer); read_fp = Popen ( " ./Outputtest " , " R " ); If (Read_fp! = Null) {chars_read = Fread (buffer, Sizeof ( Char ), Bufsiz, read_fp ); If (Chars_read>0 ) {Printf ( " Output was: \ n % s \ ndone \ n " , Buffer) ;}pclose (read_fp); exit (exit_success);} exit (exit_failure );}
The running effect is as follows:
Here we mainly useRObtain the output of the called program.
3.2Passing parameters to other programs
ToInputtestThe Code is as follows:
View code
# Include <unistd. h> # Include <Stdlib. h> # Include <Stdio. h> # Include < String . H> Int Main () {File * Write_fp; Char Buffer [bufsiz +1 ]; Sprintf (buffer, " Once... \ n " ); Write_fp = Popen ( " ./Inputtest " , " W " ); If (Write_fp! = Null) {fwrite (buffer, Sizeof ( Char ), Strlen (buffer), write_fp); pclose (write_fp); exit (exit_success);} exit (exit_failure );}
The running effect is as follows:
Here we mainly useWParameters are passed to the called program.
IV,PoepnOperation example (PythonCode)
ActuallyPythonYou can also play it like this.
4.1Obtain program output
Also mentioned aboveOutputtestThe Code is as follows:
#! /Usr/bin/PythonImportOS#Var = OS. popen ('LS-l'). Read ()Var = OS. popen ('./Outputtest'). Read ()PrintVaR
The running effect is as follows:
4.2Passing parameters to other programs
Also mentioned aboveInputtestThe Code is as follows:
#! /Usr/bin/PythonImportOsos. popen ('./Inputtest','W'). Write ("Test")
The running effect is as follows: