我该如何转换:

FILE *f;
char in_buffer[80];
f=popen("command","r");
fgets(in_buffer,sizeof(in_buffer),f)

不使用popen(),但只使用pipe()或其他指令?

最佳答案

这是我的简单实现,注释解释了正在做的事情。

#include <unistd.h>
#include <stdio.h>

FILE *
my_popen (const char *cmd)
{
    int fd[2];
    int read_fd, write_fd;
    int pid;

    /* First, create a pipe and a pair of file descriptors for its both ends */
    pipe(fd);
    read_fd = fd[0];
    write_fd = fd[1];

    /* Now fork in order to create process from we'll read from */
    pid = fork();
    if (pid == 0) {
        /* Child process */

        /* Close "read" endpoint - child will only use write end */
        close(read_fd);

        /* Now "bind" fd 1 (standard output) to our "write" end of pipe */
        dup2(write_fd,1);

        /* Close original descriptor we got from pipe() */
        close(write_fd);

        /* Execute command via shell - this will replace current process */
        execl("/bin/sh", "sh", "-c", cmd, NULL);

        /* Don't let compiler be angry with us */
        return NULL;
    } else {
        /* Parent */

        /* Close "write" end, not needed in this process */
        close(write_fd);

        /* Parent process is simpler - just create FILE* from file descriptor,
           for compatibility with popen() */
        return fdopen(read_fd, "r");
    }
}

int main ()
{
    FILE *p = my_popen ("ls -l");
    char buffer[1024];
    while (fgets(buffer, 1024, p)) {
        printf (" => %s", buffer);
    }
    fclose(p);
}

笔记:
thir代码只支持"r"模式。实现其他模式,即popen模式,留给读者作为练习。
本例中使用的系统功能可能会失败-错误处理留给读者作为练习。
"w"的实现留给读者作为练习-请参见pcloseclosewaiptid
如果你想了解真正的弹劾案,你可以调查OSXGNU glibcOpenSolaris等的来源。
希望这有帮助!

07-28 03:06
查看更多