Linux程序中执行shell(程序、脚本)并获得输出结果

本文介绍了如何利用popen函数来执行Shell命令并获取其输出。通过实例代码展示了popen函数的基本用法,包括如何创建管道、执行命令及读取结果。

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

       系统函数popen函数可以处理调用shell,其函数原型如下:

        FILE *popen(const char * command,const char *type);

        该函数的作用是创建一个管道,fork一个进程,然后执行shell,而shell的输出可以采用读取文件的方式获得。采用这种方法,既可以避免了创建临时文件,又不受输出字符的限制,推荐使用。

       popen使用FIFO管道执行外部程序。

       #include <stdio.h>
       FILE *popen(const char *command, const char *type);
       int pclose(FILE *stream);

       popen 通过type是r还是w确定command的输入/输出方向,r和w是相对command的管道而言的。r表示command从管道中读入,w表示 command通过管道输出到它的 stdout,      popen返回FIFO管道的文件流指针。pclose则用于使用结束后关闭这个指针。

#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define BUFLEN (1024)

int readconsole(char *cmd, char *buf, int buflen) {
 FILE *stream;
 int readlen;
 
 stream = popen(cmd, "r" ); 
 readlen = fread( buf, sizeof(char), buflen, stream); 

 pclose( stream );
 return readlen;
}

int main( void )
{
 char buf[BUFLEN];
 int readlen;
 
 memset( buf, '\0', BUFLEN );
 readlen = readconsole("/media/workspace/vincent/develop/app/exec/my_shell", buf, BUFLEN);
 printf("myshell len=%d,buf=%s\n", readlen, buf);
 
 return 0;
} 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值