Linux学习笔记-使用管道通信实现cat /etc/passwd | grep root这条命令
生活随笔
收集整理的這篇文章主要介紹了
Linux学习笔记-使用管道通信实现cat /etc/passwd | grep root这条命令
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
子進(jìn)程1:
執(zhí)行命令將執(zhí)行結(jié)果寫入管道
子進(jìn)程2:
從管道中讀取命令執(zhí)行的結(jié)果,然后根據(jù)關(guān)鍵字過濾
如 cat /etc/passwd | grep root這條命令
注意以下幾點(diǎn):
1.指針數(shù)組構(gòu)建參數(shù)列表;
2.匿名管道,通常是指有關(guān)系的進(jìn)程;
3.fork()函數(shù)的返回值大于0說明是父進(jìn)程;
4.子進(jìn)程創(chuàng)建完,要break下,不然會(huì)出現(xiàn)進(jìn)程鏈;
5.父進(jìn)程要等子進(jìn)程創(chuàng)建完成后再回收;
6.cat命令的默認(rèn)輸出是標(biāo)準(zhǔn)輸出(屏幕);
7.在本程序中將標(biāo)準(zhǔn)輸出重定向到管道寫端(調(diào)用dup2函數(shù)【dup to XXX】);
8.grep命令默認(rèn)讀取的內(nèi)容來源標(biāo)準(zhǔn)輸入。
?
源碼如下:
#include <unistd.h> #include <stdio.h> #include <stdlib.h>char *cmd1[3] = {"/bin/cat", "/etc/passwd", NULL}; char *cmd2[3] = {"/bin/grep", "root", NULL};int main(void){int fd[2];if(pipe(fd) < 0){perror("pipe error");exit(1);} pid_t pid;int i = 0;for(; i < 2; i++){pid = fork();if(pid < 0){perror("fork error");exit(1);}else if(pid == 0){ //child processif(i == 0){//第一個(gè)進(jìn)程負(fù)責(zé)往管道寫close(fd[0]); //關(guān)閉讀端//將標(biāo)準(zhǔn)輸出重定向到管道寫端if(dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO){perror("dup2 error");}close(fd[1]);//調(diào)用exec函數(shù)執(zhí)行cat命令if(execvp(cmd1[0], cmd1) < 0){perror("execvp error");exit(1);}break;}if(i == 1){//第二個(gè)進(jìn)程負(fù)責(zé)往管道讀close(fd[1]); //關(guān)閉寫端//將標(biāo)準(zhǔn)輸出重定向到管道的讀端if(dup2(fd[0], STDIN_FILENO) != STDIN_FILENO){perror("dup2 error");}close(fd[0]);//調(diào)用exec函數(shù)執(zhí)行g(shù)rep命令if(execvp(cmd2[0], cmd2) < 0){perror("execvp error");exit(1);}break;} }else{ //parent processif(i == 1){//父進(jìn)程要等子進(jìn)程全部創(chuàng)建完再收回close(fd[0]);close(fd[1]);wait(0);wait(0);} }}exit(0); }程序運(yùn)行截圖如下:
總結(jié)
以上是生活随笔為你收集整理的Linux学习笔记-使用管道通信实现cat /etc/passwd | grep root这条命令的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows下,使用dumpcpp 方
- 下一篇: Linux学习笔记-Makefile的基