linux进程间通信-笔记

3 篇文章 0 订阅

一、 管道

1. 匿名管道

用于进程间通信, 创建一个管道,一端写,一端读

#include <unistd.h>

int pipe(int fildes[2]);

fides[0]读取,fides[1]写入
成功返回0,失败返回-1

示例代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main()
{
    int fd[2];
    int ret = pipe(fd);
    if(ret == -1)
    {
        printf("pipe error: %s\n", strerror(errno));
    }

    pid_t pid = fork();

    if(pid == 0)
    {
        char buf[128];

        printf("before read\n");
        sleep(5);
        ssize_t chars_read = read(fd[0], buf, sizeof(buf));
        printf("end read\n");

        printf("chars_read = %ld, data = %s\n", chars_read, buf);
    }
    else if(pid > 0)
    {
        char str[] = "hello world";

        printf("before write\n");

//        sleep(5);

        ssize_t chars_write = write(fd[1], str, strlen(str));
        chars_write += write(fd[1], str, strlen(str));
        printf("end write\n");

        printf("chars_write = %ld\n", chars_write);
    }

    getchar();
    return 0;
}

通过在示例中添加额外代码测试,可知:

  1. 管道读入端会一直阻塞,直到有数据写入才返回;
  2. 写入端即使没有读入段,依旧能写入,不阻塞。
  3. 如果多次写入,读取端一次能读取到所有数据
通信速度测试
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <time.h>

int main()
{
    int fd[2];
    int ret = pipe(fd);
    if(ret == -1)
    {
        printf("pipe error: %s\n", strerror(errno));
    }

    pid_t pid = fork();

    if(pid == 0)
    {
        timespec t0, t1;
        while (true)
        {
            read(fd[0], &t0, sizeof(timespec));
            clock_gettime(CLOCK_REALTIME, &t1);
            printf("%lds, %ldns\n", t1.tv_sec - t0.tv_sec, t1.tv_nsec - t0.tv_nsec);
        }
    }
    else if(pid > 0)
    {
        timespec t0;
        while (true)
        {
            sleep(1);
            clock_gettime(CLOCK_REALTIME, &t0);
            write(fd[1], &t0, sizeof(timespec));
        }
    }

    getchar();
    return 0;
}

输出结果:

0s, 85000ns
0s, 45000ns
0s, 43000ns
0s, 31000ns
0s, 40000ns
0s, 37000ns
0s, 32000ns
0s, 40000ns
...

大约通信一次速度 35us

2. 有名管道

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值