管道简析 Linux C

管道

内核提供,单工,自同步机制(永远迁就速度慢的一方)

匿名管道

由内核维护创建,没有文件名,在文件系统上不显示,只有有亲缘关系的进程才能使用。

函数 pipe

NAME
       pipe, pipe2 - create pipe

SYNOPSIS
       #include <unistd.h>

       int pipe(int pipefd[2]);//0端为读端  1端为写端

       #define _GNU_SOURCE             /* See feature_test_macros(7) */
       #include <fcntl.h>              /* Obtain O_* constant definitions */
       #include <unistd.h>

       int pipe2(int pipefd[2], int flags);

DESCRIPTION
       pipe()  creates  a  pipe, a unidirectional data channel that can be 
       used for interprocess communication.  The array pipefd is used to 
       return two file descriptors referring to the ends  of  the  pipe. 
       pipefd[0]  refers to the read end of the pipe.  pipefd[1] refers to the 
       write end of the pipe.  Data written to the write end of the pipe is 
       buffered by the kernel until it is read from the read end of the pipe. 
       For further details, see pipe(7).

简单实例:父进程写管道 子进程读管道

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>


#define BUFSIZE 1024

int main(){

    int pd[2];
    pid_t pid;
    char buf[BUFSIZE];
    int len;

    if(pipe(pd) < 0){
        perror("pipe():");
        exit(1);
    }

    pid = fork();
    if(pid < 0){
        perror("fork():");
        exit(1);        
    }

    if(pid == 0){   //子进程读管道
        
        close(pd[1]);
        len = read(pd[0], buf, BUFSIZE);
        write(1, buf, len);
        close(pd[0]);
        exit(0);
    }
    else{           //父进程写管道

        close(pd[0]);
        write(pd[1], "Hello!\n", 7);
        close(pd[1]);
        wait(NULL);
        exit(0);
    }

}
命名管道

函数:mkfifo()

NAME
       mkfifo, mkfifoat - make a FIFO special file (a named pipe)

SYNOPSIS
       #include <sys/types.h>
       #include <sys/stat.h>
		/*
		pathname 管道文件名字
		mode	权限
		*/
       int mkfifo(const char *pathname, mode_t mode);

       #include <fcntl.h>           /* Definition of AT_* constants */
       #include <sys/stat.h>

       int mkfifoat(int dirfd, const char *pathname, mode_t mode);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值