Linux学习笔记-对父子进程直接通信基础与实例
生活随笔
收集整理的這篇文章主要介紹了
Linux学习笔记-对父子进程直接通信基础与实例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
原理
栗子
原理
實現進程通信的目的:
數據傳輸!
共享數據!
通知事件!
資源共享!
進程控制!
早期linux進程間信號(IPC)有3個部分:
目前Linux進程通信方式:
管道通信:
【注意:管道實際上是創建到計算機內核當中的緩存】
管道分類:
匿名管道:
命名管道(FIFO):
【注意可以通過操作這個管道文件就可以了,他會自動同步到緩存中】
注意:
fork子進程后,會復制父進程的數據(代碼段,數據段,堆棧等),所以fd(文件描述符)也會被復制
fork函數將運行著的程序分成2個(幾乎)完全一樣的進程,每個進程都啟動一個從代碼的同一位置開始執行的線程。這兩個進程中的線程繼續執行,就像是兩個用戶同時啟動了該應用程序的兩個副本。
?
栗子
下面是源碼,要注意:
源碼如下:
#include <unistd.h> #include <string.h> #include <stdlib.h> #include <stdio.h>int main(void){int fd[2];if(pipe(fd) < 0){perror("pipe error!");exit(1);}pid_t pid; if((pid = fork()) < 0){perror("fork error");exit(1);}else if(pid >0 ){ // parent processclose(fd[0]);int start = 1, end = 100;//往管道中寫數據if(write(fd[1], &start, sizeof(int)) != sizeof(int)){perror("write error");exit(1); }if(write(fd[1], &end, sizeof(int)) != sizeof(int)){perror("write error");exit(1);}close(fd[1]);wait(0);}else{ //child processclose(fd[1]);int start, end;if(read(fd[0], &start, sizeof(int)) < 0){perror("read error");exit(1);}if(read(fd[0], &end, sizeof(int)) < 0){perror("read error");exit(1);}close(fd[0]);printf("child process read start: %d , end: %d \n", start, end);}exit(0); }程序運行截圖如下:
總結
以上是生活随笔為你收集整理的Linux学习笔记-对父子进程直接通信基础与实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt文档阅读笔记-QHeaderView
- 下一篇: C++工作笔记-map有自动排序的功能