简体   繁体   中英

pipe fork and execvp analogs in windows

This is simple demonstration of pipe fork exec trio using in unix.

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

Now I want to write same in windows using WinAPI. What functions should I use? Any ideas?

fork() and execvp() have no direct equivalent in Windows. The combination of fork and exec would map to CreateProcess (or _spawnvp if you use MSVC). For the redirection, you need CreatePipe and DuplicateHandle, this is covered decently in this MSDN article

If you only need fork+execvp in the sense of launching another process that reads from a pipe (like in your example) then the answer given by Erik is 100% what you want (+1 on that).

Otherwise, if you need real fork behaviour, you are without luck under Windows, as there is no such thing. Though, with a lot of hacks it can be achieved, kind of. Cygwin has a working fork implementation that creates a suspended process and abuses setjmp and shared memory to get hold of its context and manually copy the stack and heap over in a somewhat complicated "dance" between parent and child. It's far from pretty and not overly efficient, but it kind of works, and it is probably as good as it can get under an operating system that doesn't natively support it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM