Linux多进程09-匿名管道实现ps aux

/*
    实现 ps aux | grep xxx
    父子进程间通信

    子进程 : ps aux, 子进程结束后将数据发送给父进程
    父进程 : 获取到数据,guolv

    pipe()
    execlp()
    子进程将标准输出 stdout_fileno 重定向到管道的写端 dup2()

*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <wait.h>

int main(int argc, char const *argv[])
{
    //创建一个管道
    int fd[2];
    int ret = pipe(fd);

    if (ret == -1)
    {
        perror("pipe err");
        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]);
        //文件描述符重定向
        dup2(fd[1], STDOUT_FILENO);
        //执行 ps aux
        execlp("ps", "ps", "aux", NULL);
        perror("execlp err");
        exit(0);
    }
    else
    {
        perror("fork err");
        exit(0);
    }

    return 0;

运行:

./pci
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  0.5 167416 11204 ?        Ss   14:44   0:08 /sbin/init splash
root           2  0.0  0.0      0     0 ?        S    14:44   0:00 [kthreadd]
root           3  0.0  0.0      0     0 ?        I<   14:44   0:00 [rcu_gp]
root           4  0.0  0.0      0     0 ?        I<   14:44   0:00 [rcu_par_gp]
root           5  0.0  0.0      0     0 ?        I<   14:44   0:00 [netns]
root           7  0.0  0.0      0     0 ?        I<   14:44   0:00 [kworker/0:0H-events_highpri]

本文作者:言叶以上

本文链接:https://www.cnblogs.com/anqwjoe/p/17409733.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   言叶以上  阅读(25)  评论(0编辑  收藏  举报
历史上的今天:
2018-05-17 Vue.js 基础知识
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起