利用pipe实现兄弟进程之间的通信
2022/1/28 7:04:20
本文主要是介绍利用pipe实现兄弟进程之间的通信,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
/* 使用pipe完成 ps aux | grep bash ************************************************************************/ #include <sys/wait.h> #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc,char* argv[]){ if(argc<2){ printf("./a.out bash"); exit(1); } //创建管道 int fd[2]; int ret = pipe(fd); int i =0; if(ret == -1){ perror("pipe error"); exit(1); } // pid_t Apid [2]; 此数组可以存储子进程pid,不过在此程序中使用 i的值来判断进程。 //创建子进程 for(i = 0;i<2;++i){ pid_t pid = fork(); if(pid == -1){ perror("fork error"); exit(1); }else if(pid == 0){ break; }else{ Apid[i]=pid; } } //if(getpid() == Apid[1]){ if(i == 0){ //child grep bush r close(fd[1]); //将标准输入重定向到管道的读端 dup2(fd[0],STDIN_FILENO); execlp("grep","grep","--color=auto",argv[1],NULL); perror("execlp error"); } if(i==1){ //child ps aux w close(fd[0]); //将标准输出重定向到管道的写端 dup2(fd[1],STDOUT_FILENO); execlp("ps","ps","a","u","x",NULL); //只有execlp失败才会往下执行 perror("execlp error"); } if(i==2){ close(fd[0]); close(fd[1]); // sleep(3); do{ ret = waitpid(-1,NULL,WNOHANG); }while(ret != -1); } return 0; }
这篇关于利用pipe实现兄弟进程之间的通信的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-01为什么公共事业机构会偏爱 TiDB :TiDB 数据库在某省妇幼健康管理系统的应用
- 2024-04-26敏捷开发:想要快速交付就必须舍弃产品质量?
- 2024-04-26静态代码分析的这些好处,我竟然都不知道?
- 2024-04-26你在测试金字塔的哪一层?(下)
- 2024-04-26快刀斩乱麻,DevOps让代码评审也自动起来
- 2024-04-262024年最好用的10款ER图神器!
- 2024-04-2203-为啥大模型LLM还没能完全替代你?
- 2024-04-2101-大语言模型发展
- 2024-04-17基于SpringWeb MultipartFile文件上传、下载功能
- 2024-04-14个人开发者,Spring Boot 项目如何部署