gpt4 book ai didi

c++ - Windows 中的 pipe fork 和 execvp 类似物

转载 作者:搜寻专家 更新时间:2023-10-31 00:03:53 26 4
gpt4 key购买 nike

这是在 unix 中使用 pipe fork exec trio 的简单演示。

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

现在我想使用 WinAPI 在 Windows 中编写相同的内容。我应该使用什么功能?有什么想法吗?

最佳答案

fork()execvp() 在 Windows 中没有直接等效项。 fork 和 exec 的组合将映射到 CreateProcess(如果您使用 MSVC,则映射到 _spawnvp)。对于重定向,您需要 CreatePipe 和 DuplicateHandle,这在 this MSDN article 中有很好的介绍。

关于c++ - Windows 中的 pipe fork 和 execvp 类似物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5181512/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com