two very useful inter-process communication functions Popen,pclose
Today from the relatively late, and then came to do not want to review, or read study-write code-write blog interesting, dare not say how proficient, at least every day in learning new knowledge, do not seek to complete digestion immediately, but to seek progress every day.
Now look at these two functions, in fact, is to create a pipeline to the child process, but the use of these two functions than yesterday using the pipe () function is much simpler.
#include <stdio.h>
FILE *popen (const char *command, const char *type);
int Pclose (FILE *stream);
The function prototype parameter. The Popen function has two parameters, and the first is an executable that executes, and the function first calls fork () and then calls the Exec () function to execute it. Then there is a parameter with two options (R & W). R: Connect the returned file pointer to the standard output of the executable program, W: Connect the returned file pointer to the standard input of the EXE file.
#include <stdio.h> #include <apue.h> #include <sys/wait.h> #include <unistd.h> #define PAGER "${ Pager:-more} "#define MAXLINE 255int Main (int Argc,char **argv) { char line[maxline]; FILE *fpin,*fpout; if (argc! = 2) { printf ("Plesase Enter the pathname\n"); } if (Fpin = fopen (Argv[1], "r")) = = NULL) { printf ("Can not open \ n"); } if (Fpout = Popen (PAGER, "w")) = = NULL) { printf ("Popen error\n"); } while (fgets (line,maxline,fpin) = NULL) { if (fputs (line,fpout) = = EOF) { printf ("fputs error\n");} } if (ferror (Fpin)) { printf ("Fgets error\n"); } if (Pclose (fpout) = =-1) { printf ("Pclose error\n"); } Exit (0);}
First of all, we should create a local text file to write something, and then passed to the program, the program calls its own more paging program, the text of the contents of the page display on the terminal.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Two very useful inter-process communication functions Popen,pclose