函數popen()

用到popen()的時候,到網上找了找,發現網上好多對man幫助裏的內容進行了解釋,有部分解釋內容如下:“popen 的返回值是個標準 I/O 流,必須由 pclose 來終止。前面提到這個流是單向的。所以向這個流寫內容相當於寫入該命令的標準輸入;命令的標準輸出和調用 popen 的進程相同。與之相反的,從流中讀數據相當於讀取命令的標準輸出;命令的標準輸入和調用 popen 的進程相同。”這話怎麼讀都彆扭,理解起來就有些難了。先來看看popen的函數聲明:FILE * popen(const char* command, const char* type)

在使用這個函數的時候,將參數type寫成“w”就出現了不能理解的地方(網上的一些程序參數type多是“r”)。看下面一個程序:

#include <stdio.h>
int main()
{
        FILE * fp;
        char buf[40] = {0};
        fp = popen(NULL, "w");
        if(NULL == fp)
        {
                perror("popen error.\n");
                return -1;
        }
        printf("Input command:");
        fgets(buf, 40, stdin);
        fputs(buf, fp);
        pclose(fp);
        return 0;
}

執行結果:

[root@localhost codetest]# ./a.out 
sh: -c: option requires an argument
Input command:pwd

很明顯出錯了,但是根據那段翻譯的內容,搞得自己很糊塗,後來問了老師,說是type參數爲"w"的時候,popen的第一個參數爲命令解釋器,即bash/sh之類。修改後的程序如下:

#include <stdio.h>
int main()
{
        FILE * fp;
        char buf[40] = {0};
        fp = popen("bash", "w");
        if(NULL == fp)
        {
                perror("popen error.\n");
                return -1;
        }
        printf("Input command:");
        fgets(buf, 40, stdin);
        fputs(buf, fp);
        pclose(fp);
        return 0;
}
執行結果:

[root@localhost codetest]# ./a.out 
Input command:pwd
/home/qian/codetest

這下就對了!

可是還是有疑問的,如果我直接在popen()的第一個參數寫命令,也同樣可以得到命令結果,程序如下:

#include <stdio.h>
int main()
{
        FILE * fp;
        char buf[40] = {0};
        fp = popen("pwd", "w");
        if(NULL == fp)
        {
                perror("popen error.\n");
                return -1;
        }
        pclose(fp);
        return 0;
}
執行結果:

[root@localhost codetest]# ./a.out 
/home/qian/codetest

關於這個參數的問題,一直是個疙瘩,如果誰知道的話,可以給個解答,感激不盡!


下面是type參數爲“r”的一個程序:

#include <stdio.h>
int main()
{
        FILE * fp;
        char buf[20] = {0};
        fp = popen("ls","r");
        if(NULL == fp)
        {
                perror("popen error!\n");
                return -1;
        }
        while(fgets(buf, 20, fp) != NULL)
        {
                printf("%s", buf);
        }
        pclose(fp);
        return 0;
}

值得注意的是:一定要用pclose()來關閉文件指針,這是我老忘記的事。


下面給出一個網上給出的popen()和pclose()實現函數:

Figure 15.12. The popen and pclose functions
#include "apue.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/wait.h>

/*
 * Pointer to array allocated at run-time.
 */
static pid_t    *childpid = NULL;

/*
 * From our open_max(), Figure 2.16.
 */
static int      maxfd;

FILE *
popen(const char *cmdstring, const char *type)
{
    int     i;
    int     pfd[2];
    pid_t   pid;
    FILE    *fp;

    /* only allow "r" or "w" */
    if ((type[0] != 'r' && type[0] != 'w') || type[1] != 0) {
        errno = EINVAL;     /* required by POSIX */
        return(NULL);
    }

    if (childpid == NULL) {     /* first time through */
        /* allocate zeroed out array for child pids */
        maxfd = open_max();
        if ((childpid = calloc(maxfd, sizeof(pid_t))) == NULL)
            return(NULL);
    }

    if (pipe(pfd) < 0)
        return(NULL);   /* errno set by pipe() */

    if ((pid = fork()) < 0) {
        return(NULL);   /* errno set by fork() */
    } else if (pid == 0) {                           /* child */
        if (*type == 'r') {
            close(pfd[0]);
            if (pfd[1] != STDOUT_FILENO) {
                dup2(pfd[1], STDOUT_FILENO);
                close(pfd[1]);
            }
        } else {
            close(pfd[1]);
            if (pfd[0] != STDIN_FILENO) {
                dup2(pfd[0], STDIN_FILENO);
                close(pfd[0]);
            }
        }

        /* close all descriptors in childpid[] */
        for (i = 0; i < maxfd; i++)
            if (childpid[i] > 0)
                close(i);

        execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
        _exit(127);
    }

    /* parent continues... */
    if (*type == 'r') {
        close(pfd[1]);
        if ((fp = fdopen(pfd[0], type)) == NULL)
            return(NULL);
    } else {
        close(pfd[0]);
        if ((fp = fdopen(pfd[1], type)) == NULL)
            return(NULL);
    }

    childpid[fileno(fp)] = pid; /* remember child pid for this fd */
    return(fp);
}


int
pclose(FILE *fp)
{
    int     fd, stat;
    pid_t   pid;

    if (childpid == NULL) {
        errno = EINVAL;
        return(-1);     /* popen() has never been called */
    }

    fd = fileno(fp);
    if ((pid = childpid[fd]) == 0) {
        errno = EINVAL;
        return(-1);     /* fp wasn't opened by popen() */
    }

    childpid[fd] = 0;
    if (fclose(fp) == EOF)
        return(-1);

    while (waitpid(pid, &stat, 0) < 0)
        if (errno != EINTR)
            return(-1); /* error other than EINTR from waitpid() */

    return(stat);   /* return child's termination status */
}


發佈了42 篇原創文章 · 獲贊 30 · 訪問量 36萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章