个人技术分享

进程间通信意味着两个不同的进程间可以交换数据,它使得不同的进程能够协同工作,实现复杂的系统功能。

1.通过管道实现进程间通信

下图是基于 管道(PIPE) 的进程间通信结构模型
在这里插入图片描述
管道不属于进程的资源,属于操作系统的资源,所以两个进程可以通过操作系统提供的内存空间进行通信,下面是创建管道的函数

int pipe(int fd[2]);
//fd数组中存储了2个文件描述符
//fd[0]表示管道出口
//fd[1]表示管道入口

下面是子进程通过管道向父进程传输信息的示例:

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

int main(){
    int fd[2];
    char str[]="hello PIPE";
    char buff[30];

    pipe(fd);
    pid_t pid=fork();
    if (pid==0)//子进程
    {
        write(fd[1],str,sizeof(str));//写入管道
    }else{//父进程
        read(fd[0],buff,sizeof(buff));//读取管道
        printf("%s\n",buff);
    }
    return 0;
    
}

在这里插入图片描述

2.通过管道进行进程间双向通信

可以采用1个管道进行,但是不稳定,所以最好的办法就是采用2个管道进行双向通信,结构如图所示
在这里插入图片描述
下面是一个示例代码,子进程和父进程都向对方发送信息

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

int main(){
    int fd1[2],fd2[2];
    char str1[]="hello PIPE";
    char str2[]="hhh, Hello";
    char buff[30];

    pipe(fd1),pipe(fd2);
    pid_t pid=fork();
    if (pid==0)//子进程
    {
        write(fd1[1],str1,sizeof(str1));//子进程写给父进程的信息  "hello PIPE"
        read(fd2[0],buff,sizeof(buff));
        printf("message from papa is: %s\n",buff);
    }else{//父进程
        write(fd2[1],str2,sizeof(str2));//父进程写给子进程的信息  "hhh, Hello"
        read(fd1[0],buff,sizeof(buff));
        printf("message fromo son is: %s\n",buff);
    }
    return 0;
    
}

在这里插入图片描述