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