Windows中的管道分支和execvp类似物

Mih*_*yan 2 c c++ winapi

这是在unix中使用的pipe fork exec三重奏的简单演示.

#include <stdio.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <sys/types.h>

int main()
{
    int outfd[2];
    if(pipe(outfd)!=0)
    {
          exit(1);
    }
    pid_t pid = fork();
    if(pid == 0)
    {
        //child
        close(outfd[0]);
        dup2(outfd[1], fileno(stdout));
        char *argv[]={"ls",NULL};
        execvp(argv[0], (char *const *)argv);
        throw;
    }
    if(pid < 0)
    {
        exit(1);
    }
    else
    {
        //parrent
        close(outfd[1]);
        dup2(outfd[0], fileno(stdin));
        FILE *fin = fdopen(outfd[0], "rt");
        char *buffer[2500];
        while(fgets(buffer, 2500, fin)!=0)
        {
            //do something with buffer
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在我想在Windows中使用WinAPI编写相同的内容.我应该使用哪些功能?有任何想法吗?

Eri*_*rik 5

fork()execvp()在Windows中没有直接的等价物.fork和exec的组合将映射到CreateProcess(如果使用MSVC,则为_spawnvp).对于重定向,您需要CreatePipe和DuplicateHandle,这在MSDN文章中有所体现