C - 不使用 popen 的管道

2024-02-20

我该如何改变这个:

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);
}

Notes:

  1. 第三个代码仅支持"r"的模式popen。实现其他模式,即"w"模式留给读者作为练习。
  2. 本示例中使用的系统函数可能会失败 - 错误处理留给读者作为练习。
  3. 实施pclose留给读者作为练习 - 请参阅close, waiptid, and fclose.

如果您想查看真实的实现,您可以查看以下来源OSX http://www.opensource.apple.com/source/Libc/Libc-186/gen.subproj/popen.c, GNU glibc http://koala.cs.pub.ro/lxr/glibc/libio/iopopen.c and 开放Solaris https://github.com/joyent/illumos-joyent/blob/master/usr/src/cmd/mailx/popen.c等。

希望这可以帮助!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C - 不使用 popen 的管道 的相关文章

随机推荐