Recently in the project to use the C language to execute the shell command problem, investigated, generally have the system function, exec family functions, but it is not clear how to get the shell command execution of the return information.
For example, to execute a ifconfig command, you definitely need to get the return value of the Ifconfig command.
When you investigate, you'll find a popen function, or you can execute the shell command, and get the return information that the shell command performs.
Man Popen can see:
#include <stdio.h>
FILE *popen (const char *command, const char *type);
int Pclose (FILE *stream);
Example:
#include <stdio.h>
#include <string.h>
int main (int argc,char*argv[]) {
FILE *fstream=null;
Char buff[1024];
memset (buff,0,sizeof (Buff));
if (null== (Fstream=popen ("Ifconfig", "R")))
{
fprintf (stderr, "Execute command failed:%s", Strerror (errno));
return-1;
}
while (null!=fgets (buff, sizeof (buff), fstream)) {
printf ("%s", buff);
}
Pclose (fstream);
return 0;
Use this example to test a mount command, accidentally put the IP address wrong, the results to the pclose, a long time did not return.
Looked at some of the data and found that Popen was creating a subprocess to execute the shell command, destroy the child process with Pclose and reclaim the resource, so Pclose will wait for the child process to exit.
So when executing a shell command with Popen, it's best to allow the shell command to return within a certain amount of time.
Add one point:
When the Mount command is executed with Popen, the Mount error message cannot be captured with the preceding code.
For example, if you deliberately write the parameters of the mount incorrectly, you cannot get the Mount error message when using Fgets, although you can see the mount error message on the terminal, but fgets cannot get it.
The idea is that the Mount error message is not output to stdout, in order to confirm the guess, the Mount command at the end of the add 2>&1, is the error message redirected to stdout, the result fgets can get the Mount error message.