匿名管道的使用

/*
- 实现 ps aux | grep ***
- 子进程:执行ps aux 子进程结束后,将数据发送给父进程
- 父进程:获取到数据,并进行过滤
- pipe()
- execlp():默认把结果输出的标准终端,需要把子进程的stdout_fileno标准输出重定向到管道的写端 dup2
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <wait.h>
int main()
{
    int fd[2];
    int ret=pipe(fd);

    if(ret==-1)
    {
        perror("pipe");
        exit(0);
    }
    
    //创建子进程-创建子进程之前创建管道
    pid_t pid=fork();
    if(pid>0)
    {
        //父进程
        //关闭写端
        close(fd[1]);

        //从管道中读取数据
        char buf[1024]={0};
        int len=-1;

        while (len=read(fd[0],buf,sizeof(buf)-1)>0)
        {
            //过滤数据然后输出
            printf("%s",buf);
            memset(buf,0,1024);//重新设置内存
        }

        wait(NULL);
    }
    else if(pid==0)
    {
        //子进程
        //关闭读端
        close(fd[0]);

        //文件描述符重定向:stdout_fileno->fd[1]
        //第一个参数:目标 第二个参数:对象
        dup2(fd[1],STDOUT_FILENO);
        //执行ps aux
        execlp("ps","ps","aux",NULL);
        perror("execlp");
        exit(0);
    }
    else
    {
        perror("foke");
        exit(0);
    }

}

posted @ 2023-02-09 11:11  小秦同学在上学  阅读(18)  评论(0编辑  收藏  举报