AllBull 2022-01-27 23:30 采纳率: 40%
浏览 11
已结题

利用pipe实现 ps aux | grep 【】 为什么无输出结果


    使用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];
    //创建子进程
    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(i==2){
        
        close(fd[0]);
        close(fd[1]);
        do{
            ret = waitpid(-1,NULL,WNOHANG);
        }while(ret != -1);
    }
    if(getpid() == Apid[1]){
        //child  grep bush r
        close(fd[1]);
        //将标准输入重定向到管道的读端
        dup2(fd[0],STDIN_FILENO);
    
        execlp("grep","grep","--color=auto",argv[1],NULL);
        perror("execlp error");
    }

    if(getpid() == Apid[0]){
        //child  ps aux   w
        close(fd[0]);
        //将标准输出重定向到管道的写端
        dup2(fd[1],STDOUT_FILENO);

        execlp("ps","ps","a","u","x",NULL);

        //只有execlp失败才会往下执行
        perror("execlp error");
    }
    return 0;

}


  • 写回答

1条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      问题事件

      • 系统已结题 2月4日
      • 已采纳回答 1月27日
      • 修改了问题 1月27日
      • 创建了问题 1月27日

      悬赏问题

      • ¥30 VB6.0操作 webview2内核的浏览器如何精确实现网页弹窗处置
      • ¥15 pr导出的视频打不开,提示“缺少编解码器”怎么解决
      • ¥15 html里js获取php参数值不成功,帮改代码
      • ¥20 如何控制ant design的InputNumber组件 最多输入5位小数
      • ¥15 c语言学生基本信息管理系统
      • ¥100 火车头采集器采集求解
      • ¥88 关于#运行时间 时间重叠 和非重叠#的问题,如何解决?
      • ¥15 C语言,密切接触者追踪
      • ¥20 关于计算机网络问题,请附带讲解
      • ¥30 自动识别图像目标并判断