天天看點

popen、system

1、popen函數

 popen()通過建立一個管道,調用 fork 産生一個子程序,執行一個 shell 以運作指令來開啟一個程序。

這個程序必須由 pclose() 函數關閉,而不是 fclose() 函數。

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

功能:執行shell指令,并讀取此指令的傳回值。

參數:command:一個指向以NULL結束的shell指令字元串的指針

      type:隻能是讀或寫("r"或"w")

傳回:如果調用fork()或pipe()失敗,或者不能配置設定記憶體将傳回NULL,否則傳回标準I/O流

2、system函數

 system()會調用fork()産生子程序,由子程序來調用/bin/sh-c string來執行參數string字元串所代表的指令,此指令執行完後随即傳回原調用的程序

#include <stdlib.h>
int system(const char *command);
           

函數:int system(const char *command)

功能:執行shell指令

傳回: -1 :fork()失敗

    127 :exec()失敗

   other:子shell的終止狀态

3、例子

#include <stdio.h>
int main()
{
    FILE *fp   = NULL;
    char buf[100] = {0};
    fp = popen("cat /tmp/test", "r");
    if(NULL == fp)
    {
        printf("popen() erro!!!");
        return -1;
    }

    while(NULL != fgets(buf, sizeof(buf), fp))
    {
        printf("%s", buf);
    }

    pclose(fp);
    return 0;
}

fp = popen("date > /tmp/test", "w");
fwrite(buf, 1, sizeof(buf), fp);