? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?兩個很有用的進程間通信函數popen,pclose
? 今天起的比較晚,然后來了也不想復習,還是看書學習--寫代碼--寫博客有意思,不敢說有多精通,至少每天都在學習新知識,不求立刻完全消化,但求每天有進步。
? 現在就看看這兩個函數,其實都是創建一個管道到子進程,但是使用這兩個函數要比昨天使用pipe() 函數簡單的多。
??? ? #include <stdio.h>
? ? ? ?FILE *popen(const char *command, const char *type);
? ? ? ?int pclose(FILE *stream);
? ? ? ?函數原型參上。popen 函數有兩個參數,第一個是執行的可執行程序,這個函數首先會調用fork( )然后調用exec( )函數執行這個可執行文件。然后還有一個參數,有兩個選項(r & w). r :將返回的文件指針連接到可執行程序的標準輸出,w:將返回的文件指針連接到可執行文件的標準輸入。
? ? ??
#include<stdio.h>
#include<apue.h>
#include<sys/wait.h>
#include<unistd.h>
#define PAGER "${PAGER:-more}"
#define MAXLINE 255
int 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);
}
首先我們應當在本地創建一個文本文件隨便寫入一些東西,然后傳給這個程序,這個程序調用本身的more 分頁程序,將文本里的東西分頁顯示在終端上。 版權聲明:本文為博主原創文章,未經博主允許不得轉載。