• 技术文章 >php教程 >PHP开发

    Linux C编程 - 管道pipe

    高洛峰高洛峰2016-12-13 11:37:19原创880
    在linux中,管道也是一种文件,只不过比较特殊,我们可以用pipe函数创建一个管道,其原型声明如下:

    #inlcude <unistd.h>

    int pipe(int fields[2]);

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

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <string.h>
    #include <errno.h>
    #include <sys/types.h>
    #include <sys/wait.h>

    #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核实处理。
    专题推荐:pipe Linux C编程
    上一篇:Linux pipe函数 下一篇:Linux命令:reboot命令
    20期PHP线上班

    相关文章推荐

    精选22门好课,价值3725元,开通VIP免费学习!• SQL Server触发器创建、删除、修改、查看• linux awk命令详解• Yii快速入门 (二)• yii2.0数据库迁移教程• javascript绝对禁止单击鼠标右键
    1/1

    PHP中文网