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

被折叠的 条评论
为什么被折叠?



