linux程序通訊-管道
阿新 • • 發佈:2018-12-14
程序通訊:也就是我們所說的IPC,包括多種形式:管道,FIFO,訊息佇列,訊號量,共享儲存。其中管道和FIFO應用於大量應用程式。
管道 管道是UNIX系統IPC最古老的形式。但它有兩種侷限性: 1)它是半雙工的,現在也有系統提供全雙工的管道,但不利於移植。 2)管道只能在具有同一個祖先的兩個程序間使用 管道建立 通過函式pipe建立
#include<unistd.h>
int pipe(int fd[2]);
成功返回0,出錯返回-1
引數fd返回兩個檔案描述符:fd[0]為讀,fd[1]為寫。fd[1]的輸出是fd[0]的輸入。 通常在父程序中,呼叫pipe,然後fork一個子程序。如果想要從父程序向子程序寫資料。則在父程序中關閉fd[0],在子程序關閉fd[1]。如果父程序從子程序讀入資料,就進行相反的操作。 程式例項
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<stddef.h> #include<unistd.h> #include<signal.h> #include<sys/types.h> #include<sys/stat.h> #include<sys/termios.h> #include<sys/ioctl.h> #include<pwd.h> #include<setjmp> int main(void) { int n; int fd[2]; pid_t pid; char line[200]; if(pipe(fd)<0) //建立管道 printf("err"); if((pid=fork())<0) //建立程序 printf("err"); else if(pid>0){ //在父程序中,關閉讀管道,寫資料到管道 close(fd[0]); write(fd[1],"hello",sizeof(line)); } else{ //在子程序中,關閉寫管道,從管道中讀資料,最後寫至標準備輸出 close(fd[1]); n=read(fd[0],line,100); write(STDOUT_FILENO,line,n); } exit(0); }
函式popen和pclose popen這個函式實現的是:建立一個管道,fork一個子程序,關閉未使用的管道端,執行一個shell命令。就是我們之前做的很多步,這一個函式就實現了。
#include<stdio.h>
FILE *popen(const char *cmdstring,const char *type);
成功返回檔案指標,出錯返回NULL
int pclose(FILE *fp)
成功返回cmdstring的終止狀態,出錯返回-1
type引數:"r"表示父程序從管道讀,"w"表示父程序從管道寫 cmdstring:shell命令,包括我們程式編譯的可執行檔案 程式例項
#include<unistd.h>
#include<signal.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/termios.h>
#include<sys/ioctl.h>
#include<pwd.h>
#include<setjmp.h>
#include<time.h>
#include<pthread.h>
#include<sys/wait.h>
#include<ctype.h>
int main()
{
char line[1000];
FILE *fpin;
if((fpin=popen("ls -l","r"))==NULL) //從管道讀取ls 輸出的資料到檔案fpin
printf("popen err\n");
for(;;){
if(fgets(line,1000,fpin)==NULL) //從檔案fpin中讀取資料到line
break;
if(fputs(line,stdout)==EOF)
printf("fputs err\n"); //將讀取的資料輸出到標準輸出流
}
if(pclose(fpin)==-1) //關閉I/O檔案
printf("close error\n");
putchar('\n');
exit(0);
}