进程间的通信----管道
前提:本文是基于Linux系統(tǒng)下的學(xué)習(xí)
用戶態(tài)的進(jìn)程是如何組織的呢?
所有的用戶態(tài)進(jìn)構(gòu)成了一棵樹。進(jìn)程樹。
進(jìn)程樹的樹根是init.也就是1號(hào)進(jìn)程。是用戶態(tài)進(jìn)程的祖宗進(jìn)程。
如何查看進(jìn)程樹?
pstree
進(jìn)程之間的關(guān)系 父子進(jìn)程和兄弟進(jìn)程
查看進(jìn)程的信息
ps -aux
實(shí)時(shí)查看進(jìn)程的使用情況 top
如何創(chuàng)建一個(gè)進(jìn)程?
fork(2) 可以創(chuàng)建一個(gè)子進(jìn)程。
#include <unistd.h>
pid_t fork(void);
功能:創(chuàng)建一個(gè)子進(jìn)程。函數(shù)的調(diào)用者是父進(jìn)程,新創(chuàng)建的進(jìn)程是子進(jìn)程
參數(shù):void
返回值:
成功 父進(jìn)程中返回子進(jìn)程的pid
子進(jìn)程中返回0
失敗 父進(jìn)程中返回-1. errno被設(shè)置
子進(jìn)程創(chuàng)建失敗
?
進(jìn)程的終止
?return和exit(3)
return 只是從函數(shù)調(diào)用中返回。結(jié)束了函數(shù)的執(zhí)行。在main函數(shù)中返回,并沒(méi)有結(jié)束進(jìn)程
exit(3) 這個(gè)函數(shù)被調(diào)用的時(shí)候,結(jié)束當(dāng)前進(jìn)程。
?
無(wú)名管道和有名管道
無(wú)名管道--應(yīng)用于具有親屬關(guān)系的進(jìn)程間通信
pipe(2)? ? 創(chuàng)建無(wú)名管道
pipefd[0] 指向讀端;pipefd[1]指向?qū)懚?/p> 1 //無(wú)名管道必須是帶有親屬關(guān)系的 父子or兄弟 2 //無(wú)名管道實(shí)現(xiàn)進(jìn)程間通信 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 //創(chuàng)建無(wú)名管道 12 int p=pipe(pfd);//pfd[0] read; pfd[1] write 13 if(p==-1){ 14 perror("pipe"); 15 return -1; 16 } 17 //創(chuàng)建子進(jìn)程 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]);//關(guān)閉讀 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 }
?
有名管道:其實(shí)就是一個(gè)文件,這個(gè)文件沒(méi)有內(nèi)容,只是起到一個(gè)橋梁的作用
mkfifo(3)
1 //mkfifo.c 2 //創(chuàng)建管道文件 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 }?
轉(zhuǎn)載于:https://www.cnblogs.com/qiuyuwutong/p/9350020.html
總結(jié)
以上是生活随笔為你收集整理的进程间的通信----管道的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: flask基础之jinja2模板-语法定
- 下一篇: ptyhon中文本挖掘精简版