1. 程式人生 > >Linux 程序間通訊的一種實現方式

Linux 程序間通訊的一種實現方式

程序間通訊的方式一般有三種:管道(普通管道、流管道和命名管道)、系統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程序都可將其讀取,用作後續操作