linux-C-简化管道操作

本文介绍了一个简单的C程序,该程序利用popen函数执行外部命令并读取其输出。通过示例展示了如何使用popen和fgets来获取命令ps的输出,并在屏幕上打印这些信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>

int main(void){
   FILE *fp;
   char *cmd="ps";
   char line[1024];
   //完成fork(),使用shell执行命令,父进程通过它得到子进程返回的文件描述符,popen简化管道操作
   fp=popen(cmd,"r");
   if (!fp){
   		perror("打开管道");
   		exit(1);
   }
   while (fgets(line,1024,fp)){
   		printf("%s",line);
   }
   return 0; 
}
 deepfuture@deepfuture-laptop:~/private/mytest$ gcc -o testpopen  testpopen.c

testpopen.c: In function ‘main’:

testpopen.c:11: warning: incompatible implicit declaration of built-in function ‘exit’

deepfuture@deepfuture-laptop:~/private/mytest$ ./testpopen

  PID TTY          TIME CMD

 2062 pts/0    00:00:00 bash

11929 pts/0    00:00:00 testpopen

11930 pts/0    00:00:00 sh

11931 pts/0    00:00:00 ps

deepfuture@deepfuture-laptop:~/private/mytest$ 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值