进程间通信
- 信号
- 管道
- 消息队列
- 共享内存
- socket实现
信号:异步通信,根据特定的情况发出信号量供其他进程相应。
管道:半双工消息传输,类似创建共享文件节点,进程双方读写该文件节点(传递字串)
消息队列:传递void*标识的数据,可以置界解析。每个消息队列都有自己的id,根据id可以拿到指定的数据。
共享内存:访问速度快,但读写同步需要信号量来控制
socket通信:ip地址+端口,实现socket的网络传输。
信号
参考文章: Linux信号(signal) 机制分析
信号实现demo
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void handler(int arg)
{
printf("hello world\n");
//kill(getpid(),9); //9表示 SIGKILL 杀死信号
}
/*
SIGIN信号: ctrl + c
当SIGINT信号发生时,调用 handler 函数处理
*/
int main(int argc, const char *argv[])
{
signal(SIGINT,handler); //定义自己的处理信号
while(1);
return 0;
}
管道
/*创建一个管道文件,类似创建文件<路径,权限>*/
int mkfifo(const char * pathname,mode_t mode); //若成功则返回0,否则返回-1,错误原因存于errno中。
命名管道demo:
client.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
/*
在创建管道前,最好用access查看是否已经存在。
管道在内存中,读写速度比较快
*/
int main()
{
int ret;
ret = mkfifo("tp",0644); //创建一个管道文件
printf("result ret = %d \n", ret);
int outfd = open("tp", O_WRONLY); //打开管道文件,读写操作
if(outfd == -1){
perror("open");
return 2;
}
char buf[] = "hello world!!!!!!!";//用于存放文件内容
while(1)
{
write(outfd,buf,sizeof(buf));
usleep(1);
}
close(outfd);
}
server.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
/*打开一个管道*/
int outfd = open("tp",O_RDONLY);//打开管道文件
if(outfd == -1)</