管道实现ps -aux | grep a.out

来源:互联网 发布:域名为什么收费 编辑:程序博客网 时间:2024/06/06 01:57
/************************************************************************* * File Name: ps_aux.c * Author: lixiaogang * Mail: 2412799512@qq.com  * Created Time: 201706月08日 星期四 2113分08秒 ************************************************************************/#include<stdio.h>#include<stdlib.h>#include<string.h>#include<sys/types.h>#include<fcntl.h>#include<unistd.h>void sys_err(const char *str,int num){    perror(str);    exit(num);}int main(int argc,char *argv[]){    int fd[2];    pid_t pid;    if(pipe(fd) != 0){        sys_err("pipe",-1);    }    pid = fork();    if(pid < 0){        sys_err("fork",-1);    }else if(pid == 0){        //ps -aux | grep a.out        close(fd[0]);        dup2(fd[1],STDOUT_FILENO);        close(fd[1]);        execlp("ps","ps","aux",NULL);        return -3;    }    pid = fork();    if(pid < 0){        sys_err("fork",-1);    } else if(pid == 0){        close(fd[1]);        dup2(fd[0],STDIN_FILENO);        close(fd[0]);        execlp("grep","grep","a.out",NULL);    }    wait(NULL);    wait(NULL);    close(fd[0]);    close(fd[1]);    return 0;}
原创粉丝点击