popen 如何获取指令执行情况,在c中使用popen运行多个命令

Im creating a program using C that runs in a linux environment that needs to run multiple commands like this

sudo -s

ls

pwd

(assume that the commands under sudo -s are commands that needs to be super user to be able to run it)

Now, what I need to do is get all the output of these commands for further processing.

Here's the code

int executeCommand(char *command, char *result)

{

/*This function runs a command./*/

/*The return value is the output of command*/

int nSuccess = -1;

FILE * fp = NULL;

char buffer[1035];

if (command == NULL)

render("Command is null");

if (result == NULL)

render("result is null");

if (command!=NULL && result!=NULL)

{

fp=popen("sudo -s","w");

fwrite ( " ls", 1, 3, fp);

fwrite ( " pwd", 1, 4, fp);

if(fp!=NULL)

{

strcpy(result,"\0");

while(fgets(buffer, sizeof(buffer)-1,fp)!=NULL)

{

strcat(result,buffer);

}

pclose(fp);

} nSuccess=0;

}

return nSuccess;

}

The question is how will I be able to execute ls and pwd and then get it's output? Thank you :)

解决方案

Formally speaking, there is no quesion in your post, but

if your problem is that ls and pwd are not executed by sudo -s:Try adding a newline to the fwrite()s (as you would type in your shell as well):

fwrite ( "ls\n", 1, 3, fp);

fwrite ( "pwd\n", 1, 4, fp);

(a " " before the command shouldn't be neccessary)

Don't call fwrite() before checking fp

if you call fp=popen("sudo -s","w");, you can't use fp for reading. while(fgets(buffer, sizeof(buffer)-1,fp)!=NULL) won't work. If you want to pipe commands to sudo and want to read the output, you need two pipes what makes things a little more complicated, or maybe you can redirect sudo's output to a temp file and read that afterwards:

char tmpfile[L_tmpnam];

char cmd[1024];

tmpnam( tmpfile );

sprintf( cmd, "sudo -s >%s", tmpfile );

fp = popen( cmd, "w" );

....

pclose(fp);

FILE *ofp = fopen( tmpfile, "r" );

if( rfp != null ) {

while(fgets(buffer, sizeof(buffer)-1,rfp)!=NULL)

{

strcat(result,buffer);

}

fclose( rfp );

remove( tmpfile );

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值