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 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2018-05-17 Vue.js 基础知识