进程间的通信(无名管道)

进程间通信 IPC

InterProcess Communication

1.进程间通信方式

1.早期的进程间通信:

无名管道(pipe)、有名管道(fifo)、信号(signal)

2.system V PIC:

共享内存(share memory)、信号灯集(semaphore)、消息队列(message queue)

3.BSD:

套接字(socket)

2.无名管道

2.1 特点

  1. 只能用于具有亲缘关系的进程之间的通信
  2. 半双工的通信模式,具有固定的读端fd[0]和写端fd[1]。
  3. 管道可以看成是一种特殊的文件,对于它的读写可以使用文件IO如read、write函数。
  4. 管道是基于文件描述符的通信方式。当一个管道建立时,它会创建两个文件描述符 fd[0]和fd[1]。其中fd[0]固定用于读管道,而fd[1]固定用于写管道。

2.2 函数接口

int pipe(int fd[2])
功能:创建无名管道
参数:文件描述符 fd[0]:读端  fd[1]:写端
返回值:成功 0
       失败 -1

读写特性:

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

int main(int argc, char const *argv[])
{
    char buf[65536] = "";
    int fd[2] = {0}; //fd[0]代表读端,fd[1]代表写端
    if (pipe(fd) < 0)
    {
        perror("pipe err");
        return -1;
    }
    printf("%d %d\n", fd[0], fd[1]);

    //结构类似队列,先进先出
    //1. 当管道中无数据时,读阻塞。
    // read(fd[0], buf, 32);
    // printf("%s\n", buf);

    //但是关闭写端就不一样了
    //当管道中有数据关闭写端可以读出数据,无数据时关闭写端读操作会立即返回。
    // write(fd[1], "hello", 5);
    // close(fd[1]);
    // read(fd[0], buf, 32);
    // printf("%s\n", buf);

    //2. 当管道中写满数据时,写阻塞,管道空间大小为64K
    // write(fd[1], buf, 65536);
    // printf("full!\n");
    //write(fd[1], "a", 1);  //当管道写满时不能再继续写了会阻塞

    //写满一次之后,当管道中至少有4K空间时(也就是读出4K),才可以继续写,否则阻塞。
    // read(fd[0], buf, 4096); //换成4095后面再写就阻塞了,因为不到4K空间
    // write(fd[1], "a", 1);

    //3. 当读端关闭,往管道中写入数据无意义,会造成管道破裂,进程收到内核发送的SIGPIPE信号。
    close(fd[0]);
    write(fd[1], "a", 1);
    printf("read close\n");

    return 0;
}


用gdb调试可以看见管道破裂信号:

gcc -g xx.c

gdb a.out

r

2.3 注意事项

1.当管道中无数据时,读操作会阻塞。

   管道中有数据,将写端关闭,可以将数据读出。

   管道中无数据,将写端关闭,读操作会立即返回。

2.管道中装满(管道大小64K)数据写阻塞,一旦有4k空间,写继续。

3.只有在管道的读端存在时,向管道中写入数据才有意义。否则,会导致管道破裂,向管道中写入数据的进程将收到内核传来的SIGPIPE信号 (通常Broken pipe错误)。

练习题:父子进程实现通信,父进程循环从终端输入数据,子进程循环打印数据,当输入quit结束。

提示:不需要加同步机制, 因为pipe无数据时读会阻塞。

先创建管道再fork,这样父子进程可以使用同一个无名管道。

参考代码:

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

int main(int argc, char const *argv[])
{
    pid_t pid;
    char buf[32] = "";
    int fd[2];
    if (pipe(fd) < 0)
    {
        perror("pipe err");
        return -1;
    }
    printf("%d %d\n", fd[0], fd[1]);

    pid = fork();
    if (pid < 0)
    {
        perror("fork err");
        return -1;
    }
    else if (pid == 0) //循环打印, quit结束
    {
        while (1)
        {
            read(fd[0], buf, 32); //读出管道中内容存入buf
            if (strcmp(buf, "quit") == 0)
                break;
            printf("%s\n", buf);//将buf内容打印到终端
        }
    }
    else //循环输入,quit结束
    {
        while (1)
        {
            scanf("%s", buf);
            write(fd[1], buf, 32); //把输入buf内容写入管道
            if (strcmp(buf, "quit") == 0)
                break;
        }
        wait(NULL);
    }

    return 0;
}

练习题:请在linux 利用c语言编程实现两个线程按照顺序依次输出”ABABABAB......" 

例如a线程输出”A”之后b线程输出”B”,然后a线程输出“A”,再b线程输出”B”,之后往复循环。

信号量实现(方法一):

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
#include<unistd.h>

char buf[32];
sem_t sem0;
sem_t sem1;

void *handler_thread(void *arg)
{
    while (1)
    {
        //申请资源 sem0
        sem_wait(&sem0); //P操作, -1
        printf("B");
        fflush(NULL);
        //释放资源 sem1
        sem_post(&sem1);
        sleep(1);
    }
}

int main(int argc, char const *argv[])
{
    pthread_t tid;
    if (sem_init(&sem0, 0, 0) != 0)
    {
        perror("sem init 0 err");
        return -1;
    }

    if (sem_init(&sem1, 0, 1) != 0)
    {
        perror("sem init 1 err");
        return -1;
    }

    if (pthread_create(&tid, NULL, handler_thread, NULL) != 0)
    {
        perror("pthread err");
        return -1;
    }

    while (1)
    {
        //申请资源 sem1
        sem_wait(&sem1);
        printf("A");
        fflush(NULL);
        sem_post(&sem0); //V操作,+1
        sleep(1);
    }

    return 0;
}



条件变量实现(方法二):

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t lock;
pthread_cond_t cond;

void *funA(void *arg)
{
    sleep(2);
    while (1)
    {
        sleep(1);
        pthread_mutex_lock(&lock);
        printf("A");
        fflush(NULL);
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&lock);
    }

    pthread_exit(NULL);
}
void *funB(void *arg)
{
    sleep(1);
    while (1)
    {
        pthread_mutex_lock(&lock);
        pthread_cond_wait(&cond, &lock);
        printf("B ");
        fflush(NULL);
        pthread_mutex_unlock(&lock);
    }
    putchar('\n');
    pthread_exit(NULL);
}

int main(int argc, char const *argv[])
{
    pthread_t tid1, tid2;
    pthread_cond_init(&cond, NULL);
    pthread_mutex_init(&lock, NULL);

    if (pthread_create(&tid1, NULL, funA, NULL) < 0)
    {
        perror("tid1 err");
        return -1;
    }
    if (pthread_create(&tid2, NULL, funB, NULL) < 0)
    {
        perror("tid1 err");
        return -1;
    }

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值