日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

文件进程间通信

發布時間:2023/11/30 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 文件进程间通信 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

使用文件也可以完成IPC,理論依據是,fork后,父子進程共享文件描述符。也就共享打開的文件。

//父子進程共享打開的文件。借助文件進行進程間通信(可先打開文件,再創建子進程)

#include <unistd.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <stdio.h> #include <sys/wait.h>int main(void) {int fd1, fd2; pid_t pid;char buf[1024];char *str = "---------test for shared fd in parent child process-----\n";pid = fork();if (pid < 0) {perror("fork error");exit(1);} else if (pid == 0) {fd1 = open("test.txt", O_RDWR);if (fd1 < 0) {perror("open error");exit(1);}write(fd1, str, strlen(str));printf("child wrote over...\n");} else {fd2 = open("test.txt", O_RDWR);if (fd2 < 0) {perror("open error");exit(1);}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 <stdio.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <string.h>#define N 10int main(void) {char buf[1024];char *str = "--------------secesuss-------------\n";int ret;int fd = open("test.txt", O_RDWR|O_TRUNC|O_CREAT, 0664);//直接打開文件寫入數據write(fd, str, strlen(str));printf("test1 write into test.txt finish\n");sleep(N);lseek(fd, 0, SEEK_SET); //文件讀寫指針置于開始處ret = read(fd, buf, sizeof(buf));ret = write(STDOUT_FILENO, buf, ret);if (ret == -1) {perror("write second error");exit(1);}close(fd);return 0; }

//進程2(后執行,嘗試讀取進程1寫入文件的內容)

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <string.h>int main(void) {char buf[1024];char *str = "----------test2 write secesuss--------\n";int ret;sleep(2); //睡眠2秒,保證test1將數據寫入test.txt文件int fd = open("test.txt", O_RDWR); //打開文件,讀寫指針位于開頭處ret = read(fd, buf, sizeof(buf)); //嘗試讀取test.txt文件中test1寫入的數據write(STDOUT_FILENO, buf, ret); //將讀到的數據打印至屏幕write(fd, str, strlen(str)); //寫入數據到文件test.txt中, 未修改讀寫位置printf("test2 read/write finish\n");close(fd);return 0; }

[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可以獲取;反之,一樣。

總結

以上是生活随笔為你收集整理的文件进程间通信的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。