檔案程序間通訊

2021-09-14 04:11:45 字數 1842 閱讀 5753

使用檔案也可以完成ipc,理論依據是,fork後,父子程序共享檔案描述符。也就共享開啟的檔案。

//父子程序共享開啟的檔案。借助檔案進行程序間通訊(可先開啟檔案,再建立子程序)

#include #include #include #include #include #include int main(void)

else if (pid == 0)

write(fd1, str, strlen(str));

printf("child wrote over...\n");

} else

sleep(1); //保證子程序寫入資料

int len = read(fd2, buf, sizeof(buf));

write(stdout_fileno, buf, len);

wait(null);

}return 0;

}

[root@localhost mmap]# ./fork_share_fd

child wrote over...

---------test for shared fd in parent child process-----

另外,無血緣關係的程序也可以開啟同乙個檔案進行通訊,方法一樣,因為這些程序開啟的是同乙個程序。其實在開啟檔案時(呼叫open時),作業系統核心就呼叫了mmap。因為乙個檔案只有乙個檔案結構體(file),開啟時位於核心,被開啟這個檔案的多個程序共享。

//程序1(先執行,將資料寫入檔案test.txt

#include #include #include #include #include #define n 10

int main(void)

close(fd);

return 0;

}

//程序2(後執行,嘗試讀取程序1寫入檔案的內容)

#include #include #include #include #include int main(void)

[root@localhost file_ipc]# ./test1

test1 write into test.txt finish

--------------secesuss-------------

----------test2 write secesuss--------

[root@localhost file_ipc]# ./test2

--------------secesuss-------------

test2 read/write finish//通過檔案,程序1寫入的資料,程序2可以獲取;反之,一樣。

php程序間通訊 yoc PHP程序間通訊

php是用c編寫的,因此它對系統底層api的操作與c很像,同大多數語言一樣,php程序間通訊的方式有以下幾種 訊息佇列,管道,共享記憶體,socket和訊號。本文是對這幾種通訊方式對整理 管道通訊pipe 管道用於承載簡稱之間的通訊資料。為了方便理解,可以將管道比作檔案,程序a將資料寫到管道p中,然...

程序間通訊

實現程序間資料共享除了常用的記憶體檔案對映外,對於一些非檔案的資料共享可以直接使用wm copydata。如果需要在程序a傳遞資料到程序b,簡單的實現如下 在程序a中 cstring strdatatosend t hello 需要傳遞的資料 hwnd hwndreceived 程序b的接收資料視窗...

程序間通訊

最近做專案遇到奇怪的問題,我在主線程中建立乙個工作執行緒。在工作執行緒中用sendmessage向主線程傳送訊息,通知主線程操作office 物件。getactiveobject時提示 hr 0x8001010d 因為應用程式正在傳送乙個輸入同步呼叫,所以無法執行傳出的呼叫。我把sendmessag...