操作系统 管道及其实现
生活随笔
收集整理的這篇文章主要介紹了
操作系统 管道及其实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*7.“grep –o”不會輸出包含某字符串的行,而只會把匹配的字符串輸出(有幾個匹配就輸出幾次,且每行輸出一個匹配字符串),
因而可以用 “grep –o xxx file | wc -l”來統(tǒng)計文件file中“xxx”字符串出現了多少次。
請用多進程pipe程序實現該功能(此前先用which命令查一下grep命令和wc命令在哪個目錄),
要求:創(chuàng)建一個文本文件為zhangsan,自己在該文件中輸入若干數目的字符串“zhangsan”,將其作為操作的原材料。
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<unistd.h>
#define MSGSIZE 24int main(int argc,char *argv[])
{int status;int pid[2],pipe_fd[2];char *prog1_argv[]={"/bin/grep","-o",argv[1],argv[2],NULL};char *prog2_argv[]={"/usr/bin/wc","-l",NULL};//create the pipeif(pipe(pipe_fd)<0){perror("pipe failed\n");exit(errno);}//兄弟之間管道if((pid[0]=fork())<0){perror("fork failed\n");exit(errno);}//pid[0]==0,即進入子進程if(!pid[0]){close(pipe_fd[0]);dup2(pipe_fd[1],1);//pipe_fd[1]指向STDOUT_FILENO,即輸出重定向close(pipe_fd[1]);//裝載一個新的程序,并將其轉換到調用進程的內存空間,也即向管道寫入execvp(prog1_argv[0],prog1_argv);}//回到父進程if(pid[0]){if((pid[1]=fork())<0){perror("fork failed\n");exit(errno);}if(!pid[1]){close(pipe_fd[1]);dup2(pipe_fd[0],0);//pipe_fd[0]指向STDIN_FILENO,即輸入重定向close(pipe_fd[0]);//裝載一個新的程序,并將其轉換到調用進程的內存空間,也即向管道寫入execvp(prog2_argv[0],prog2_argv);}close(pipe_fd[0]);close(pipe_fd[1]);waitpid(pid[0],&status,0);waitpid(pid[1],&status,0);}return 0;
}
友情鏈接:
(1)UNIX管道應用及Shell實現(一)-主體框架
https://blog.csdn.net/crazy_scott/article/details/79548331
(2)UNIX管道應用及Shell實現(二)-命令解析
https://blog.csdn.net/crazy_scott/article/details/79548325
(3)Linux–實現一個簡易的Shell(可以獲取命令提示符,支持管道)
https://blog.csdn.net/xu1105775448/article/details/80311274
(4)Linux進程間通信(二)—管道通信之無名管道及其基礎實驗
https://blog.csdn.net/mybelief321/article/details/9073895
(5)Linux進程間通信(三)—管道通信之有名管道及其基礎實驗
https://blog.csdn.net/mybelief321/article/details/9075229
(6)Linux進程間通信(九)—綜合實驗之有名管道通信實驗
https://blog.csdn.net/mybelief321/article/details/9196629
總結
以上是生活随笔為你收集整理的操作系统 管道及其实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Oracle11g Direct NFS
- 下一篇: IntelliJ IDEA 版本破解教程