C language returns Shell results, C language returns shell
In Linux programming, if we need to call shell commands or scripts, we usually use the system method. For example, system ("ls ")
The return value of this method is 0 or-1, that is, success or failure. In some cases, what should we do if we want to obtain the results of shell command execution?
We can redirect the shell command results to the file and then read the file, such:
System ("ls> result.txt ")
FILE * fp = fopen (result, "r ")
You can also directly use pipelines, as shown 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){ 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 calls the shell command to create a new process for execution, the execution speed is very slow, it is best not to use C, Shell Mixed Programming.