欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Linux 进程间通信的一种实现方式

程序员文章站 2022-07-14 12:41:45
...

进程间通信的方式一般有三种:管道(普通管道、流管道和命名管道)、系统IPC(消息队列、信号和共享存储)、套接字(Socket)

本博客以之前所做的智能车项目为例,简单介绍下共享存储的一种实现过程。简单说来,进程1将数据写入到一个公共文件input.txt中,进程2对其进行逐行读取。为保证读取过程的正常进行且每次读到新的数据,进程1每写一行前会清空当前行,写完后立即释放文件的写入权。

读写进程代码

在需要写入结果的时候打开文件,写完后立即关闭。

// 写进程write.cpp:
// ios::trunc 表示每次写之前清空文件
// ios::app 表示将新内容接续到旧文件后面
while(1){
    ofstream in("home/process2/input.txt", ios::trunc)
    string msg2send = "For process communication";
    in << msg2send;
    in.close();
}

/**********************************************************/

// 读进程read.cpp
while(1) {
    string tmp_input;
    getline(cin, tmp_input);
}

 

编译执行

编译write.cpp文件

编译执行write.cpp所在目录下的脚本input.sh

#!/bin/sh

nohup sudo /home/process1/videoRobot_run > ./run1.log 2>&1 &
nohup tail -f home/process2/input.txt | home/process2/read > run2.log 2>&1 &

此脚本执行后,将内容输出到input.txt文件*进程2读取

编译read.cpp文件

编译执行read.cpp文件所在目录下的read.sh

tail -f input.txt | ./read

至此,write进程每写一行内容到input.txt后,read进程都可将其读取,用作后续操作