c语言——进程间通信

进程间通信

  • 信号
  • 管道
  • 消息队列
  • 共享内存
  • 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)</
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值