ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

Linux系统编程:使用C在C中创建管道“popen()” and “pclose()”Linux中的系统调用

前开发者教程 2020年5月22日

在本章中,我们将学习:

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+章
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的


    <font id="g6M28BT"></font>