首页 php教程 PHP开发 Linux C编程 - 管道pipe

Linux C编程 - 管道pipe

Dec 13, 2016 am 11:37 AM

在linux中,管道也是一种文件,只不过比较特殊,我们可以用pipe函数创建一个管道,其原型声明如下:

#inlcude 

int pipe(int fields[2]);

其实它相当于一个通信缓冲区,fields[0]用来读,fields[1]用来写。下面的例子中,创建一个管道作为通信缓冲区,父进程创建了一个子进程,子进程通过管道的fields[1]描述符想管道中写入一个字符串,而父进程则利用管道的fields[0] 从管道中读取这个字串并显示出来:

#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define BUF_SIZ    255     // message buffer size

int main(int argc, char **argv)
{
    char buffer[BUF_SIZ + 1];
    int fd[2];

// receive a string as parameter
    if ( argc != 2)
    {
        fprintf(stderr, "Usage: %s string\n\a", argv[0]);
        exit(1);
    }

// create pipe for communication
    if ( pipe(fd) != 0 )
    {
        fprintf(stderr, "Create pipe error: %s\n\a", strerror(errno));
        exit(1);
    }

    if ( fork() == 0 )     // in child process write msg to pipe
    {
        close(fd[0]);
        printf("Child %ld write to pipe\n\a", getpid()); 
        snprintf(buffer, BUF_SIZ, "%s", argv[1]);
        write(fd[1], buffer, strlen(buffer));
        printf("Child %ld quit.\n\a", getpid());
    }
    else     // in parent process, read msg from pipe
    {
        close(fd[1]);
        printf("Parent %ld read from pipe\n\a", getpid());
        memset(buffer, '\0', BUF_SIZ + 1);
        read(fd[0], buffer, BUF_SIZ);
        printf("Parent %ld read : \n%s\n", getpid(), buffer);
        exit(1);
    }
    return 0;
}


本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1677
14
CakePHP 教程
1431
52
Laravel 教程
1334
25
PHP教程
1280
29
C# 教程
1257
24