天天看點

linux下C和shell調用的popen函數

說明:

     本文介紹popen函數的使用方法和行為機理,并給出實際的例子來輔助說明了popen函數的使用方法。

popen函數使用FIFO管道執行外部程式,首先讓我們看看popen的函數原型吧:

#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則用于使用結束後關閉這個指針。

下面一起來看一個例子:

/*******************************************************************************************

** Name:popen.c

**      This program is used to show the usage of popen() .

*******************************************************************************************/

#include <sys/types.h> 

#include <unistd.h> 

#include <stdlib.h> 

#include <stdio.h> 

#include <string.h>

int main( void ) 

   FILE   *stream; 

   FILE   *wstream;

   char   buf[1024]; 

    memset( buf, '\0', sizeof(buf) );//初始化buf,以免後面寫如亂碼到檔案中

    stream = popen( "ls -l", "r" ); //将“ls -l”指令的輸出 通過管道讀取(“r”參數)到FILE* stream

    wstream = fopen( "test_popen.txt", "w+"); //建立一個可寫的檔案

    fread( buf, sizeof(char), sizeof(buf), stream); //将剛剛FILE* stream的資料流讀取到buf中

    fwrite( buf, 1, sizeof(buf), wstream );//将buf中的資料寫到FILE    *wstream對應的流中,也是寫到檔案中

    pclose( stream ); 

    fclose( wstream );

    return 0;

}  

[root@localhost src]# gcc popen.c 

[root@localhost src]# ./a.out   

[root@localhost src]# cat test_popen.txt 

總計 128

-rwxr-xr-x 1 root root 5558 09-30 11:51 a.out

-rwxr-xr-x 1 root root 542 09-30 00:00 child_fork.c

-rwxr-xr-x 1 root root 480 09-30 00:13 execve.c

-rwxr-xr-x 1 root root 1811 09-29 21:33 fork.c

-rwxr-xr-x 1 root root 162 09-29 18:54 getpid.c

-rwxr-xr-x 1 root root 1105 09-30 11:49 popen.c

-rwxr-xr-x 1 root root 443 09-30 00:55 system.c

-rwxr-xr-x 1 root root    0 09-30 11:51 test_popen.txt

-rwxr-xr-x 1 root root 4094 09-30 11:39 test.txt

繼續閱讀