shell c 混合编程 system 输出数据到变量【转】

转自:http://www.cnblogs.com/wangkangluo1/archive/2012/02/08/2342597.html

shell c 混合编程 system 输出数据到变量

 

shell c 混合编程 system 输出数据到变量

方法一: (popen)

复制代码
#include <stdio.h>
#include <stdlib.h>


int main( int argc, char *argv[] )
{

FILE *fp;
int status;
char path[1035];

/* Open the command for reading. */
fp = popen("/bin/ls /etc/", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit;
}

/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s", path);
}

/* close */
pclose(fp);

return 0;
}
复制代码



方法二:

复制代码
#include <stdio.h>
#include <stdlib.h>



static int my_system(const char* pCmd, char* pResult, int size)
{
int fd[2];
int pid;
int count;
int left;
char* p = 0;
int maxlen = size - 1;
memset(pResult, 0, size);
if(pipe(fd))
{
printf("pipe error\n");
return -1;
}
if((pid = fork()) == 0)
{// chile process
int fd2[2];
if(pipe(fd2))
{
printf("pipe2 error\n");
return -1;
}
close(1);
dup2(fd2[1],1);
close(fd[0]);
close(fd2[1]);
system(pCmd);
read(fd2[0], pResult, maxlen);
pResult[strlen(pResult)-1] = 0;
write(fd[1], pResult, strlen(pResult));
close(fd2[0]);
exit(0);
}
// parent process
close(fd[1]);
p = pResult;
left = maxlen;
while((count = read(fd[0], p, left))) {
p = count;
left -= count;
if(left == 0)
break;
}
close(fd[0]);
return 0;
}
int main(void)
{
char result[1025];
my_system("LC_ALL=C ifconfig", result, 1025);
printf("the result is\n\n%s\n", result);
return 0;
}
复制代码


转载于:https://www.cnblogs.com/Leo-Forest/archive/2012/06/24/2560464.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值