Linux进程间通信,代码简单,一看就懂。

1、无名管道

关键函数

pipe();
write();
read();
close();

代码

#include<unistd.h>
#include<stdio.h>
int main(void) {
    int fd[2];//定义管道
    pipe(fd);//创建管道,失败返回-1
    pid_t pid = fork();//返回值为进程pid,子进程返回0,失败返回-1
    if (pid == 0) {
        //子进程读
        close(fd[1]);//子进程关闭写管道
        char line[100];//定义缓冲区
        int n = read(fd[0], line, 100);//读数据,阻塞IO模型,返回读取长度
        printf("%d %s\n",n, line);
    }
    else {
        //父进程写
        close(fd[0]);//父进程关闭读管道
        write(fd[1], "Hello!", 6);//写数据,失败返回-1
    }
    getchar();
    return 0;
}

2、有名管道(FIFO)

关键函数

mkfifo();
open();
write();
read();
close();

代码

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

#define FD "/tmp/fifo" //有名管道利用的是文件

int main(void) {
    unlink(FD);//删除已有的fifo,否则文件存在时会创建失败
    if(mkfifo(FD, 0777)==-1)//创建FIFO,0777是八进制的linux权限,失败返回-1
    { }
    pid_t pid = fork();
    if (pid == 0) {
        //子进程读
        int readfd = open(FD, O_RDONLY);//打开读FIFO
        char line[100];//创建缓冲区
        int n = read(readfd, line, 100);//读管道
        printf("%d %s\n", n, line);
        close(readfd);
    }
    else {
        //父进程写
        int writefd = open(FD, O_WRONLY);//打开写FIFO
        sleep(1);
        write(writefd, "Hello?", 6);//写管道
        close(writefd);
    }
    getchar();
    return 0;
}
  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值