day08(IO进程)进程间的通信---管道

无名管道

1. 特点

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

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

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;
}

有名管道

1. 特点

  1. 有名管道可以使互不相关的两个进程互相通信。
  2. 有名管道可以通过路径名来指出,并且在文件系统中可见,但内容存放在内存中。但是读写数据不会存在文件中,而是在管道中。
  3. 进程通过文件IO来操作有名管道。
  4. 有名管道遵循先进先出规则
  5. 不支持如lseek() 操作

2. 函数接口

int mkfifo(const char *filename,mode_t mode);
功能:创健有名管道
参数:filename:有名管道文件名
       mode:权限
返回值:成功:0
       失败:-1,并设置errno号
注意对错误的处理方式:
如果错误是file exist时,注意加判断,如:if(errno == EEXIST)

注:函数只是在路径下创建管道文件,往管道中写的数据依然写在内核空间。

先创建有名管道,然后用文件IO操作:打开、读写和关闭。

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

int main(int argc, char const *argv[])
{
    if (mkfifo("./fifo", 0777) < 0)
    {
        if (errno == EEXIST)   //如果错误号信息是已存在则打印提示语句
            printf("file exist!\n");
        else
        {
            perror("mkfifo err");
            return -1;
        }
    }
    printf("mkfifo success\n");

    return 0;
}

3.注意事项

  1. 只写方式打开阻塞,一直到另一个进程把读打开
  2. 只读方式打开阻塞,一直到另一个进程把写打开
  3. 可读可写,如果管道中没有数据,读阻塞
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char const *argv[])
{
    char buf[32] = "";
    if (mkfifo("./fifo", 0777) < 0)
    {
        if (errno == EEXIST) //如果错误号信息是已存在则打印提示语句
            printf("file exist!\n");
        else
        {
            perror("mkfifo err");
            return -1;
        }
    }
    printf("mkfifo success\n");

    //打开文件
    int fd = open("./fifo", O_RDWR);

    //读写操作
    write(fd, "hello", 5);
    read(fd, buf, 32);
    printf("%s\n", buf);
    return 0;
}


练习:通过两个进程实现cp功能。

./input srcfile

./output destfile

input.c 读源文件

//创建有名管道

//打开管道文件和源文件

//循环读源文件,写入管道

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

int main(int argc, char const *argv[])
{
    int fd_fifo, fd_file;
    char buf[32] = "";
    ssize_t s;
    if (mkfifo("fifo", 0666) < 0)
    {
        if (errno == EEXIST) 
            printf("file exist!\n"); 
        else
        {
            perror("mkfifo err");
            return -1;
        }
    }
    printf("mkfifo success!\n");

    //打开文件
    fd_fifo = open("fifo", O_WRONLY);
    fd_file = open(argv[1], O_RDONLY);
    
    if (fd_fifo < 0)
    {
        perror("open err");
        return -1;
    }

    if (fd_file < 0)
    {
        perror("open err");
        return -1;
    }

    //读源文件,写入管道
    while (1)
    {
        s = read(fd_file,buf,32);    //从文件读到buf中
        if(s == 0)
            break;
        write(fd_fifo,buf,s);        //把buf中数据写进有名管道
    }
    
    close(fd_fifo);
    close(fd_file);
    return 0;
}

ouput.c 写目标文件

//创建有名管道

//打开管道文件和目标文件

//循环读管道,写入目标文件

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

int main(int argc, char const *argv[])
{
    int fd_fifo, fd_file;
    char buf[32] = "";
    ssize_t s;
    if (mkfifo("fifo", 0666) < 0)
    {
        if (errno == EEXIST)
            printf("file exist!\n");
        else
        {
            perror("mkfifo err");
            return -1;
        }
    }
    printf("mkfifo success!\n");

    //打开文件
    fd_fifo = open("fifo", O_RDONLY);
    fd_file = open(argv[1], O_WRONLY | O_CREAT |O_TRUNC,0666);
    
    if (fd_fifo < 0)
    {
        perror("open err");
        return -1;
    }

    if (fd_file < 0)
    {
        perror("open err");
        return -1;
    }

    //读管道,写入目标文件
    while (1)
    {
        s = read(fd_fifo,buf,32);    //从有名管道中读数据到buf
        if(s == 0)
            break;
        write(fd_file,buf,s);        //把buf中数据写到
    }
    
    close(fd_fifo);
    close(fd_file);
    return 0;
}

4. 有名管道和无名管道的区别

无名管道

有名管道

使用场景

具有亲缘关系的进程间

不相干的进程可以使用

特点

半双工通信方式

固定的读端fd[0]和写端fd[1]

看作一种特殊的文件可以通过文件操作

再文件系统中会存在管道文件,数据放在内核空间中

通过文件IO进行操作

遵循先进先出,不支持lseek操作

函数

pipe()

直接read/write

mkfifo()

先打开open,再读写read/write

读写特性

当管道中无数据读阻塞

当管道中写满时写阻塞

关闭读端,往管道中写会管道破裂

只写方式打开会阻塞,直到另一个进程把读打开

只读方式打开会阻塞,直到另一个进程把写打开

可读可写打开,如果管道中无数据读阻塞

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值