Linux系统编程之管道通信

@TOC

无名管道(半双工)

局限性

  1. 数据自己读不能自己写。

  2. 数据一旦被读走,便不在管道中存在,不可反复读取。

  3. 由于管道采用半双工通信方式。因此,数据只能在一个方向上流动。

  4. . 只能在有公共祖先的进程间使用管道。
    pipe的demo:

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

int main()
{
    //int pipe(int pipefd[2]);
    int fd[2];
    char *buf = NULL;
    buf = (char*)malloc(128);

    if(pipe(fd) == -1){
        printf("creat pipe failed\n");
    }
    pid_t pid = fork();
        if(pid < 0){              //for>0为父进程
            printf("creat process failed\n");
        }else if(pid > 0){
            printf("this is father process\n");
            close(fd[0]);
            write(fd[1],"hello world", strlen("hello world"));
            wait(NULL);

        }else{
            printf("this is child process\n");
            close(fd[1]);
            read(fd[0],buf,128);
            printf("read form father %s\n",buf);
            exit(0);
        }

    return 0;
}

有名管道(全双工)

特点:不相关的两个进程可以进行通信
FIFO的demo
读端兼创建命名管道:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
//  int mkfifo(const char *pathname, mode_t mode);  
    char buf[1024] = {'\0'};
    int n_read;

    if((mkfifo("./file",0600)==-1) && errno!=EEXIST){
        printf("pipe failed\n");
        perror("why");
    }   
    
    int fd = open("./file",O_RDONLY);
    printf("open success\n");
    while(1){

        n_read = read(fd,buf,512);
        printf("read %d byte,str:%s\n",n_read,buf);         
    
    }   

    close(fd);
    return 0;
}

写端:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main()
{
    int cnt = 0;                                            
    char *str = "messag from fifo";
    
    int fd = open("./file",O_WRONLY);
    printf("write open success\n");
    while(1){
        write(fd,str,strlen(str));
        sleep(1);
        cnt++;
        //printf("%d\n",cnt);
        if(cnt==5){
            break;
        }
    }   
    close(fd);
    
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值