When Linux is programmed, the system method is usually used if we need to invoke a shell command or script. such as System ("LS")
The method returns a value of 0 or-1, that is, success or failure. And sometimes we want to get the result of the shell command execution, what do we do?
We can redirect the shell command results to a file, and then read the file, such as:
System ("Ls>result.txt")
FILE *FP = fopen (result, "R")
Of course, we can also use the pipeline directly, as in the following example:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h >
#include <strings.h>
#include <string.h>
char* shellcmd (char* cmd, char* buff, int size) c7/>{
Char temp[256];
file* fp = NULL;
int offset = 0;
int Len;
fp = popen (cmd, "R");
if (fp = = null)
{return
null;
}
while (fgets (temp, sizeof (temp), FP)!= NULL)
{
len = strlen (temp);
if (offset + len < size)
{
strcpy (buff+offset, temp);
offset = len;
else
{
Buff[offset] = 0;
break;
}
}
if (FP!= NULL)
{
pclose (FP);
}
return buff;
}
int main (void)
{
char buff[1024];
memset (buff, 0, sizeof (buff));
printf ("%s", Shellcmd ("ls", buff, sizeof (buff));
return 0;
}
Note: The C language call Shell command is a new process executed, the execution speed is very slow, preferably not C, Shell mixed programming.
Above the C language to obtain the results of the shell return to the implementation of the result is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.