在c中使用popen运行多个命令

我使用C创建一个程序,该程序在需要运行多个命令的linux环境中运行

sudo -s

LS

PWD

(假设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然后获得它的输出? 谢谢 :)

从forms上讲,你的post中没有任何问题,但是

  1. 如果你的问题是sudo -s没有执行lspwd :尝试在fwrite()添加换行符(就像你在shell中输入的那样):

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

    (命令之前的" "不应该是必要的)

  2. 在检查fp之前不要调用fwrite()

  3. 如果你调用fp=popen("sudo -s","w"); ,你不能用fp阅读。 while(fgets(buffer, sizeof(buffer)-1,fp)!=NULL)不起作用。 如果你想将命令传递给 sudo 想要读取输出,你需要两个管道使事情变得复杂一点,或者你可以将sudo的输出重定向到临时文件并在之后读取:

     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 ); }