從Linux程序中執行shell(程序、腳本)並獲得輸出結果(轉)


在學習unix編程的過程中,發現系統還提供了一個popen函數,可以非常簡單的處理調用shell,其函數原型如下:

FILE *popen(const char *command, const char *type);

該函數的作用是創建一個管道,fork一個進程,然後執行shell,而shell的輸出可以採用讀取文件的方式獲得。採用這種方法,既避免了創建臨時文件,又不受輸出字符數的限制,推薦使用。

popen使用FIFO管道執行外部程序。

#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);

popen 通過type是r還是w確定command的輸入/輸出方向,r和w是相對command的管道而言的。r表示command從管道中讀入,w表示 command通過管道輸出到它的stdout,popen返回FIFO管道的文件流指針。pclose則用於使用結束後關閉這個指針。

下面看一個例子:

//
//getconsole.c
//

#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define BUFLEN    (1024)

int readconsole(char *cmd, char *buf, int buflen) {
    FILE *stream;
    int readlen;
    
    stream = popen(cmd, "r" ); //將“ls -l”命令的輸出 通過管道讀取(“r”參數)到FILE* stream
    readlen = fread( buf, sizeof(char), buflen, stream); //將剛剛FILE* stream的數據流讀取到buf中

    pclose( stream );
    return readlen;
}

int main( void )
{
    char buf[BUFLEN];
    int readlen;
    
    memset( buf, '\0', BUFLEN );//初始化buf,以免後面寫如亂碼到文件中
    readlen = readconsole("ls", buf, BUFLEN);
    printf("ls len=%d,buf=%s\n", readlen, buf);
    
    return 0;
}

編譯:

gcc -o getconsole ./getconsole.c


說明:這個是簡略修改版本

原文出處:http://hi.baidu.com/tihu1111/blog/item/98e41c3d3a621ae23c6d9744.html



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章