在GNU Linux C程式設計中,要想進行系統指令的執行的話,隻提供了system接口,但是此接口并不能得到指令執行後所輸出的值,而隻能夠得到指令是否執行成功的結果。僅僅這樣的功能還是不夠的,有的時候是要必須通過指令的輸出來判斷下一步的結果或步驟的,那麼怎麼樣能夠得到system指令執行的結果呢?那就可以使用到popen函數和fgets函數進行指令的輸出資訊的擷取了,實際例子如下:
注意:此接口隻能夠擷取指令輸出的最後一行的資訊,若有多行輸出資訊将不能夠全部擷取到,此封裝接口隻适用于得到指令執行結果的最後一行的資訊。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int super_system(const char * cmd, char *retmsg, int msg_len)
{
FILE * fp;
int res = -1;
if (cmd == NULL || retmsg == NULL || msg_len < 0)
{
printf("Err: Fuc:%s system paramer invalid!\n", __func__);
return 1;
}
if ((fp = popen(cmd, "r") ) == NULL)
perror("popen");
printf("Err: Fuc:%s popen error: %s\n", __func__, strerror(errno));
return 2;
else
memset(retmsg, 0, msg_len);
while(fgets(retmsg, msg_len, fp));
{
printf("Fuc: %s fgets buf is %s\n", __func__, retmsg);
}
if ( (res = pclose(fp)) == -1)
printf("Fuc:%s close popen file pointer fp error!\n", __func__);
return 3;
//drop #012 from system result retmsg.
retmsg[strlen(retmsg)-1] = '\0';
return 0;
}
int main()
char *cmd = "whoami";
char *cmd1 = "initctl list";
char retmsg[1024] = {0};
int ret = 0;
ret = super_system(cmd, retmsg, sizeof(retmsg));
printf("system ret is %d retmsg is \n%s\n", ret, retmsg);
return 0;
main函數中使用了whoami的指令,執行結果即是目前使用者名。
執行結果:
linuxidc@ufo:~$ ./a.out
Fuc: super_system fgets buf is linuxidc
system ret is 0 retmsg is
linuxidc
/*********************************************************************
* Author : Samson
* Date : 03/13/2015
* Test platform:
* 3.13.0-24-generic
* GNU bash, 4.3.11(1)-release
* *******************************************************************/