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混合編程。
以上這篇C語言獲取Shell返回結果的實現方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答
圖片精選