【发布时间】:2014-04-25 09:09:29
【问题描述】:
我正在使用 C 创建一个程序,该程序在需要运行多个这样的命令的 linux 环境中运行
sudo -s
ls
密码
(假设sudo -s下的命令是需要超级用户才能运行的命令)
现在,我需要做的是获取这些命令的所有输出以进行进一步处理。 这是代码
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;
}
问题是我如何能够执行 ls 和 pwd 然后得到它的输出?谢谢你:)
【问题讨论】: