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条回答 默认 最新

  • AllBull 2022-01-27 23:43
    关注

    兄弟进程中的Apid数组中的 数据 是不全面的 。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

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

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)