popen函數是標準c提供的一個管道創建函數,其內部操作主
要是創建一個管道,調用fork創建子進程,關閉不需用的文件描述符,調用exec函數族執行popen的第一個參數。然後等到關閉。
也就是說我們可以傳遞一個命令(ls -l......)或一個可執行程序。於pipe對比來說代碼相對少很多。
**************************************************
相關函數:
#include <stdio.h>
FILE *popen(const char *command, const char *type);
1.command:shell命令或可執行程序名
2.type打開方式,可類比fopen函數
返回值:成功返回文件指針,失敗返回NULL
int pclose(FILE *stream);
返回值:成功返回command終止狀態,失敗返回-1
**************************************************
實例:
實現從終端得到字符並將大寫轉換爲小寫輸出。
分析:
編寫一個程序實現從終端得到字符並處理過濾後寫入標準輸出,
然後編譯成可執行文件。在另一個程序調用popen去執行這個可執行程序。並從文件流中讀取數據
代碼:
1.filename: popen_filter.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXLINE 1024
int main(void)
{
FILE *fpin = NULL;
char line[MAXLINE];
if ((fpin = popen("./filter", "r")) == NULL) {
perror("popen error");
return EXIT_FAILURE;
}
for (; ;) {
fputs("prompt> ", stdout);
fflush(stdout);
if (fgets(line, MAXLINE, fpin) != NULL) {
if (fputs(line, stdout) == EOF) {
perror("fputs error");
return EXIT_FAILURE;
}
} else {
break;
}
}
if (pclose(fpin) == -1) {
perror("pclose error");
return EXIT_FAILURE;
}
putchar('\n');
return EXIT_SUCCESS;
}
2.filename: filter.c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
char c;
while ((c = getchar()) != EOF) {
if (isupper(c)) {
c = tolower(c);
}
if (putchar(c) == EOF) {
perror("output error");
}
if (c == '\n') {
fflush(stdout);
}
}
return EXIT_SUCCESS;
}