在linux下怎么样才能创建一个子进程,并对子进程的stdin和stdout进行读写呢?网上查不到相关的资料。1 应用场景不是fork,是调用另外一个可执行文件。
2 system函数只能创建子进程,不能对其标准输入输出进行读写。
3 popen仅能获取输入流或者输出流,不能同时获取。

解决方案 »

  1.   

    1. 调用另一个执行文件的本质是 fork +exec
    2. system 的本质是 fork +  exec + wait
    3. popen 的本质是 fork + pipe + wait用两个 pipe 创建 两个管道 即可#include <sys/types.h>
    #include <unistd.h>#include <stdio.h>
    #include <string.h>static void
    parent(int in, int out)
    {
            ssize_t len; 
            char buf[64];        sprintf(buf, "parent: pid=%d\n", getpid());
            len = strlen(buf);
            write(out, buf, strlen(buf));        len = read(in, buf, sizeof(buf));
            if (len > 0) {
                    buf[len] = '\0';
                    printf("from child: \n[%s]\n", buf);
            }
    }static void
    child(int in, int out)
    {
            dup2(in, STDIN_FILENO);
            dup2(out, STDOUT_FILENO);
            execlp("cat", "cat", "-", (char *)0);
    }int
    main(int argc, char *argv[])
    {        pid_t pid;
            int infds[2];
            int outfds[2];        pipe(infds);
            pipe(outfds);        printf("parent: pid=%d\n", getpid());        pid = fork();
            if (pid > 0) {
                    parent(outfds[0], infds[1]);
            } else {
                    child(infds[0], outfds[1]);
            }        return 0;
    }