在本章中,我们将学习:
1.简介
2. Function prototype for popen()
3. Function prototype for pclose()
4. Simple example for popen()
介绍:
Using popen() and pclose() system calls, it is fairy easy to create pipes.
Function prototype for popen()
FILE *popen ( char *command, char *type);
It will return new file stream 上 success and NULL 上 unsuccessful fork() or 管() call.
这将在内部调用pipe()系统调用。它将执行“command”Shell中的参数。
“type” can be “r” or “w”, for “read” or “write”.
Pipe created with popen() needs to be closed using pclose().
Function prototype for pclose()
int pclose( FILE *stream );
pclose将等待管道进程终止,然后关闭流。
Simple example for popen()
#include <stdio.h> #include <stdlib.h> #define MAXSTRS 5 int main(void) { int cntr; FILE *pipe_fp; char *strings[MAXSTRS] = { "a", "d", "b","c", "e"}; /* Create 上 e way pipe line with call to popen() */ if (( pipe_fp = popen("sort", "w")) == NULL) { perror("popen"); exit(1); } /* Processing loop */ for(cntr=0; cntr<MAXSTRS; cntr++) { fputs(strings[cntr], pipe_fp); fputc('\n', pipe_fp); } /* Close the pipe */ pclose(pipe_fp); return(0); }
关于半双工管道的注意事项:
*您可以通过打开2个管道并正确地重新分配fd来创建2路管道’s.
* 管() call should be made before fork() call.
*对于“pipe()”应该有一个祖先过程。但是,在命名管道中不是这种情况。
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |