进程间的通信----管道
生活随笔
收集整理的這篇文章主要介紹了
进程间的通信----管道
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前提:本文是基于Linux系統下的學習
用戶態的進程是如何組織的呢?
所有的用戶態進構成了一棵樹。進程樹。
進程樹的樹根是init.也就是1號進程。是用戶態進程的祖宗進程。
如何查看進程樹?
pstree
進程之間的關系 父子進程和兄弟進程
查看進程的信息
ps -aux
實時查看進程的使用情況 top
如何創建一個進程?
fork(2) 可以創建一個子進程。
#include <unistd.h>
pid_t fork(void);
功能:創建一個子進程。函數的調用者是父進程,新創建的進程是子進程
參數:void
返回值:
成功 父進程中返回子進程的pid
子進程中返回0
失敗 父進程中返回-1. errno被設置
子進程創建失敗
?
進程的終止
?return和exit(3)
return 只是從函數調用中返回。結束了函數的執行。在main函數中返回,并沒有結束進程
exit(3) 這個函數被調用的時候,結束當前進程。
?
無名管道和有名管道
無名管道--應用于具有親屬關系的進程間通信
pipe(2)? ? 創建無名管道
pipefd[0] 指向讀端;pipefd[1]指向寫端
1 //無名管道必須是帶有親屬關系的 父子or兄弟 2 //無名管道實現進程間通信 3 #include <stdio.h> 4 #include <unistd.h> 5 #include <string.h> 6 #include <stdlib.h> 7 int main(){ 8 char buf[128]; 9 char* msg="hello,father\n"; 10 int pfd[2]; 11 //創建無名管道 12 int p=pipe(pfd);//pfd[0] read; pfd[1] write 13 if(p==-1){ 14 perror("pipe"); 15 return -1; 16 } 17 //創建子進程 18 pid_t pid=fork(); 19 if(pid==-1){ 20 perror("fork"); 21 return -1; 22 } 23 if(pid==0){//son 24 close(pfd[0]);//關閉讀 25 write(pfd[1],msg,strlen(msg)); 26 close(pfd[1]); 27 exit(0); 28 } 29 else{//father 30 close(pfd[1]); 31 int r=read(pfd[0],buf,128); 32 write(1,buf,r); 33 close(pfd[0]); 34 wait(NULL); 35 } 36 return 0; 37 }?
有名管道:其實就是一個文件,這個文件沒有內容,只是起到一個橋梁的作用
mkfifo(3)
1 //mkfifo.c 2 //創建管道文件 3 #include <stdio.h> 4 #include <sys/types.h> 5 #include <sys/stat.h> 6 7 int main(int argc,char* argv[]){ 8 int mk=mkfifo(argv[1],0644); 9 if(mk==-1){ 10 perror("mkfifo"); 11 return -1; 12 } 13 return 0; 14 } //fifo_w.c #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> int main(int argc,char* argv[]){char* msg="hello.read\n";//打開管道文件int fd=open(argv[1],O_WRONLY);if(fd==-1){perror("open");return -1;}//向管道文件中寫 write(fd,msg,strlen(msg));close(fd);return 0; } 1 //fifo_r.c 2 #include <stdio.h> 3 #include <sys/types.h> 4 #include <sys/stat.h> 5 #include <fcntl.h> 6 7 int main(int argc, char* argv[]){ 8 char buf[128]; 9 int fd=open(argv[1],O_RDONLY); 10 if(fd==-1){ 11 perror("open"); 12 return -1; 13 } 14 int r=read(fd,buf,128); 15 write(1,buf,r); 16 close(fd); 17 return 0; 18 }?
轉載于:https://www.cnblogs.com/qiuyuwutong/p/9350020.html
總結
以上是生活随笔為你收集整理的进程间的通信----管道的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: flask基础之jinja2模板-语法定
- 下一篇: ptyhon中文本挖掘精简版