进程间通信(1)

本文介绍了在不使用标准的Linux进程间通信(IPC)机制时,如何利用文件操作实现两个进程间的简单通信。示例中,一个进程读取标准输入并将数据写入到文件data.txt,另一个进程则不断读取该文件并显示内容,实现了数据的传递。

Linux进程间通信

不同IPC的应用场合

  • 无名管道:只能用于亲缘关系的进程
  • 有名管道:任意两进程间通信
  • 信号量: 进程间同步,包括system V信号量、POSIX信号量
  • 消息队列:数据传输,包括system V消息队列,POSIX消息队列
  • 共享内存:数据传输,包括system V共享内存,POSIX共享内存
  • 信号:主要用于进程间异步通信
  • Linux新增API:signalfd、timerfd、eventfd
  • Socket IPC:不同主机不同进程之间的通信
  • D-BUS:用于桌面应用程序之间的通信

没有学以上的方法,可以使用以前的文件操作:

/**********************************
*@file 1.c
*@brief  
*@author lizhuofan
*@date 2022-03-09
*************************************/


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
 	printf("write process pid: %d\n", getpid());
	char buf[64] = {0};
	int n = 0;
	while(1)
	{
		if ((n = read(STDIN_FILENO, buf, 64)) > 0)
		{
			int fd = open("data.txt", O_WRONLY|O_CREAT, 0664);
			if (fd < 0)
			{
				perror("open");
				exit(-1);	
			}
			buf[n] = '\0';
			write(fd, buf, n+1);
			close(fd);
		}
	}
	return 0;
}

/**********************************
*@file 2.c
*@brief  
*@author lizhuofan
*@date 2022-03-09
*************************************/


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char *argv[])
{
 	char buf[64];

	printf("read process pid: %d\n", getpid());
	int fd = open("data.txt", O_RDONLY);
	if (fd < 0)
	{
		perror("open");
		exit(-1);
	}

	int len = 0;
	while(1)
	{
		if ((len = read(fd, buf, 64)) < 0)
		{
			perror("read");
			close(fd);
			exit(-1);
		}
		printf("%s" ,buf);
		lseek(fd, SEEK_SET, 0);
		sleep(5);
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值