標準管道(popen),標準管道popen
NAME popen, pclose - pipe stream to or from a processSYNOPSIS #include <stdio.h> FILE *popen(const char *command, const char *type); int pclose(FILE *stream);DESCRIPTION The popen() function opens a process by creating a pipe, forking, and invoking the shell. Since a pipe is by definition unidirectional, the type argument may specify only reading or writing, not both; the resulting stream is correspondingly read-only or write-only. The command argument is a pointer to a null-terminated string contain- ing a shell command line. This command is passed to /bin/sh using the -c flag; interpretation, if any, is performed by the shell. RETURN VALUE The popen() function returns NULL if the fork(2) or pipe(2) calls fail, or if it cannot allocate memory. The pclose() function returns -1 if wait4(2) returns an error, or some other error is detected.
寫
popen.c,如下:
/************************************************************************* > File Name: popen.c > Author: KrisChou > Mail:zhoujx0219@163.com > Created Time: Fri 22 Aug 2014 11:07:26 AM CST ************************************************************************/#include <stdio.h>#include <stdlib.h>#include <string.h>int main(int argc, char *argv[]){ char buf[1024]; FILE *fp; while(memset(buf,0,1024),fgets(buf,1024,stdin) != NULL) { fp = popen(argv[1],"w"); fputs(buf,fp); pclose(fp); } return 0;}
被調用函數reverse.c,如下:
/************************************************************************* > File Name: reverse.c > Author: KrisChou > Mail:zhoujx0219@163.com > Created Time: Sat 23 Aug 2014 11:21:27 AM CST ************************************************************************/#include <stdio.h>#include <stdlib.h>#include <string.h>int main(int argc, char *argv[]){ char word[256]; //從標準輸入讀取字串 char buf[256][256],index = 0; //儲存從標準輸入讀取的字串 while(memset(word,0,256), scanf("%s",word) != EOF ) { strcpy(buf[index++],word); } index--; while(index >=0 ) { printf("%s ",buf[index]); index--; } printf("\n"); return 0;}
運行程式:
[purple@localhost popen]$ gcc popen.c -o main[purple@localhost popen]$ gcc reverse.c -o reverse[purple@localhost popen]$ ./main ./reversehow are youyou are howbaby u r beautifulbeautiful r u baby[purple@localhost popen]$
按 ctrl+D 退出popen.c中的迴圈,從而退出程式。
linuxC對於popen、pclose
這個函數的功能應該是讀取目前的目錄下的內容的
popen可以啟動一個新的進程,ls -l則是要啟動進程得程式名和參數,ls -l當然即使列出目錄的意思咯
"r"是代表調用進程可以通過返回的檔案指標讀取到新啟動的進程的輸出。也可以是"w",這樣調用進程就可以通過向檔案寫內容而新啟動的進程從標準輸入讀取。事實上這就是進程間的管道通訊。
popen返回一個檔案指標,返回null 指標也就是0即出錯咯。
下面的while迴圈,就是把返回的檔案的內容讀取到傳入的sck檔案描述符所指向的檔案中,fileno是把檔案指標轉換為檔案描述符
pclose函數就是關閉這個管道,它的傳回值是新啟動的這個程式的退出碼,
一般來說程式都返回0代表正確嘛,非零當然就表示程式可能有問題,如果是pclose函數錯誤會返回-1
管道標識國家標準是什
全部資訊
進階會員資訊
最新資訊
同時有188人正在找"管道標識國家標準"資訊,發布此類資訊,讓客戶主動找到你!
出售電廠鍋爐專用管道
新舊程度:不限供貨總量:多噸型號規格:不限交易價格:電議或面議所在地區:內蒙古存放方式:不限
本公司發布的其它供求資訊 點此查看更多赤峰宇恒商貿有限公司
連絡人:徐先生 | 所在地:內蒙古