歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 可以返回執行結果的system函數加強版本

可以返回執行結果的system函數加強版本

日期:2017/3/1 9:30:49   编辑:Linux編程

在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
* *******************************************************************/

Copyright © Linux教程網 All Rights Reserved