进程通信简介
进程通信(inter—process communication,IPC),是指在两个或者多个不同进程间传递或交换信息,通过信息的传递简历几个进程间的联系,协调一个系统中的多个进程之间的行为。
不通进程间的通信本质使用过不同的进程看到一份公共的资源来实现通信。
进程的通信方式
进程件的通信方式主要有:
1、管道
2、消息队列
3、共享内存
4、信号量
5、信号
6、socket
匿名管道:在我们内核中开辟一块空间,进行信息的存储,
它是一种特殊文件
特点:半双工的面向字节流的单向通信方式
适用于有亲缘关系的进程之间进行通信。
#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <sys/wait.h>int main(int argc,char *argv[]){pid_t pid=fork();int count =5;if(pid ==-1){return -1;}else if(pid ==0){sleep(10);printf("subprocess\n");}else{printf("parent %d\n",getpid());wait(NULL);printf("wait finish\n");}return 0;}/*************************************************************************> File Name: vfork.c> Author: LiSongPeng> Description:> Created Time: Thu 18 Mar 2021 02:35:26 PM CST************************************************************************/#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <sys/types.h>#include <sys/wait.h>int main(int argc,char *argv[]){int count =5;count = count+5;printf("start: %d\n",getpid());pid_t pid =vfork();if(pid == -1){printf("creat process fail!\n");}if(pid > 0){printf("父进程:=%d\n",pid);printf("%d\n",count);}else if(pid == 0){printf("子进程:%d\n",count);printf("subprocess get id=%d\n",pid);exit(0);}printf("end\n");return 0;}/*************************************************************************> File Name: pipe.c> Author: LiSongPeng> Description:> Created Time: Fri 19 Mar 321 03:05:42 PM CST************************************************************************/#include <stdio.h>#include <unistd.h>int main(int argc,char *argv[]){int p[2];int ret=pipe(p);//管道创建if(ret == -1){printf("管道创建失败");return -1;}write(p[1],"hello world",3);//管道写入,若传输字符小于字符串个数则只会传输前3个字符。close(p[1]);//关闭写端char buff[100]={0};read(p[0],buff,20);//管道读取printf("%s\n",buff);close(p[0]);//关闭写端return 0;}//1)可以像操作文件一样使用read和write函数对管道进行操作,也可以使用close进行关闭。//2)管道可以用在单进程中,但无现实意义。//3)读段指定的字节数大于写端字节数,则读端按照写段实际长度进行读取。//4)读端在读取数据时,如果管道数据为空,读端会发生阻塞。
小结:
1)可以像操作文件一样使用read的和write函数对管道进行操作,也可以使用close进行关闭
2)管道可以用在单进程中,只是没有太大的现实意义
3)读端指定的字节数打羽写段写入的字节数,则读端按照写端实际长度进行读取
4)读端在读取数据时,如果管道数据为空,读端会发生阻塞
进程的退出:正常退出和异常退出
正常退出1.遇到主函数的return
2.通过使用exit()实现进程的正常推出 wait拿到值
3._exit()
异常退出:abort()异常退出
