Linux編程時候,如果我們需要調用shell命令或腳本通常使用system方法。如system("ls")
該方法返回值為0或-1,即成功或失敗。而有的時候我們想要獲取shell命令執行的結果,該怎麼辦呢?
我們可以將shell命令結果重定向到文件中,然後再讀取這個文件,如:
system("ls>result.txt")
FILE *fp = fopen(result, "r")
當然我們也可以直接使用管道,如下面示例:
#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;
}
注意:C語言調用shell命令是新建一個進程執行的,執行速度很慢,最好不要C、Shell混合編程。