生活随笔
收集整理的這篇文章主要介紹了
操作系统 管道及其实现
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
/*7.“grep –o”不會(huì)輸出包含某字符串的行,而只會(huì)把匹配的字符串輸出(有幾個(gè)匹配就輸出幾次,且每行輸出一個(gè)匹配字符串),
因而可以用 “grep –o xxx file | wc -l”來(lái)統(tǒng)計(jì)文件file中“xxx”字符串出現(xiàn)了多少次。
請(qǐng)用多進(jìn)程pipe程序?qū)崿F(xiàn)該功能(此前先用which命令查一下grep命令和wc命令在哪個(gè)目錄),
要求:創(chuàng)建一個(gè)文本文件為zhangsan,自己在該文件中輸入若干數(shù)目的字符串“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,即進(jìn)入子進(jìn)程if(!pid[0]){close(pipe_fd[0]);dup2(pipe_fd[1],1);//pipe_fd[1]指向STDOUT_FILENO,即輸出重定向close(pipe_fd[1]);//裝載一個(gè)新的程序,并將其轉(zhuǎn)換到調(diào)用進(jìn)程的內(nèi)存空間,也即向管道寫(xiě)入execvp(prog1_argv[0],prog1_argv);}//回到父進(jìn)程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]);//裝載一個(gè)新的程序,并將其轉(zhuǎn)換到調(diào)用進(jìn)程的內(nèi)存空間,也即向管道寫(xiě)入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管道應(yīng)用及Shell實(shí)現(xiàn)(一)-主體框架
https://blog.csdn.net/crazy_scott/article/details/79548331
(2)UNIX管道應(yīng)用及Shell實(shí)現(xiàn)(二)-命令解析
https://blog.csdn.net/crazy_scott/article/details/79548325
(3)Linux–實(shí)現(xiàn)一個(gè)簡(jiǎn)易的Shell(可以獲取命令提示符,支持管道)
https://blog.csdn.net/xu1105775448/article/details/80311274
(4)Linux進(jìn)程間通信(二)—管道通信之無(wú)名管道及其基礎(chǔ)實(shí)驗(yàn)
https://blog.csdn.net/mybelief321/article/details/9073895
(5)Linux進(jìn)程間通信(三)—管道通信之有名管道及其基礎(chǔ)實(shí)驗(yàn)
https://blog.csdn.net/mybelief321/article/details/9075229
(6)Linux進(jìn)程間通信(九)—綜合實(shí)驗(yàn)之有名管道通信實(shí)驗(yàn)
https://blog.csdn.net/mybelief321/article/details/9196629
總結(jié)
以上是生活随笔為你收集整理的操作系统 管道及其实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。