文件进程间通信
使用文件也可以完成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可以獲取;反之,一樣。
總結
- 上一篇: 成都欢乐谷大摆锤多少度
- 下一篇: mmap内存映射、system V共享内