linux進程間通信-筆記

一、 管道

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. 有名管道

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章