/********************************************************************* * Author:samson * date:03/13/2015 * Test PL Atform: * 3.13.0-24-generic * GNU bash, 4.3.11 (1)-release * *********************************** ********************************/
In GNU Linux C programming, the system interface is provided only if the command is executed, but the interface does not have the value that is output after the command executes, but only the result of a successful command execution. Just such a function is not enough, sometimes it is necessary to pass the output of the command to determine the next result or step, then how to get the results of the system command execution? You can use the Popen function and the fgets function to obtain the output information of the command, the actual example is as follows:
Note : This interface is only able to obtain information from the last line of the command output, and if more than one line of output information is not fully available, this wrapper interface only applies to the information of the last line that gets the result of the command execution.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int Super_system (const char * cmd, char *retmsg, int msg_len)
{
FILE * FP;
int res =-1;
if (cmd = = NULL | | retmsg = NULL | | Msg_len < 0)
{
printf ("err:fuc:%s system Paramer invalid!\n", __func__);
return 1;
}
if (fp = popen (cmd, "r")) = = = NULL)
{
Perror ("Popen");
printf ("err:fuc:%s popen Error:%s\n", __func__, Strerror (errno));
return 2;
}
Else
{
memset (retmsg, 0, Msg_len);
while (Fgets (retmsg, Msg_len, FP));
{
printf ("Fuc:%s fgets buf is%s\n", __func__, retmsg);
}
if (res = pclose (fp)) = =-1)
{
printf ("fuc:%s close Popen file pointer fp error!\n", __func__);
return 3;
}
Drop #012 from system result retmsg.
Retmsg[strlen (RETMSG)-1] = ' + ';
return 0;
}
}
int main ()
{
Char *cmd = "WhoAmI";
Char *cmd1 = "Initctl list";
Char retmsg[1024] = {0};
int ret = 0;
ret = Super_system (cmd, retmsg, sizeof (RETMSG));
printf ("System ret is%d retmsg is \n%s\n", ret, retmsg);
return 0;
}
The WhoAmI command is used in the main function, and the result is the current user name.
Execution Result:
[Email protected]:~$./a.out
Fuc:super_system fgets BUF is UFO
System RET is 0 retmsg is
Ufo
You can return the enhanced version of the system function that executes the result