popen C函数获取linux命令的执行结果

#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<string>
#include<iostream>
using namespace std;

string get_ttyUSBn(string name)
{		
	FILE *stream;
	char buf[1024];
	memset(buf, '\0', sizeof(buf));
	string strcmd= "sh ~/get_ttyUSBnbyName.sh ";
	strcmd+=name;	
	//cout<<"shell cmd: "<<strcmd<<endl;
	const char *chcmd= strcmd.data();
	stream = popen( chcmd,"r");
	fread(buf,sizeof(char), sizeof(buf),stream);
	pclose( stream );
	string tmp(buf);
	return tmp;
}

int main()
{
	string strresult=get_ttyUSBn("mySmartUSB");
	//const char *chres= strresult.data();
	//printf("%s",chres);
	//cout<<strlen(chres)<<endl;	
	cout<<strresult;
	return 0;
}


介绍:

POPEN(3)                                      Linux Programmer's Manual                                      POPEN(3)

NAME
       popen, pclose - pipe stream to or from a process

SYNOPSIS
       #include <stdio.h>

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

       int pclose(FILE *stream);

   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

       popen(), pclose():
           _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE || _BSD_SOURCE || _SVID_SOURCE



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值