2013-03-21 67 views
0

我需要能够将fork()用于小型项目。问题是,示例代码不工作:fork()未声明的错误

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

int main() 
{ 
    pid_t pID = fork(); 
    if (pID == 0) // child 
    { 
     printf("CHILD\n"); 
     // Code only executed by child process 
    } 
    else if (pID < 0) // failed to fork 
    { 
     printf("FAIL\n"); 
    } 
    else // parent 
    { 
     printf("PARENT\n"); // Code only executed by parent process 
    } 
    // Code executed by both parent and child. 

    system("PAUSE"); 
    return 0; 
} 

编译器说:“20 d:\ Untitled1.cpp'叉”未申报(第一次使用此功能)”

但我已经在读互联网,它应该位于#include <unistd.h>

任何想法?谢谢!

+6

IIRC,Windows没有'fork()'。 * *在* POSIX *系统的'unistd.h'中。 (Windows不是100%符合POSIX的。) – cdhowie 2013-03-21 18:04:24

+0

那么这个速度很快,你知道我可以使用的其他功能做同样的事吗?谢谢! – 2013-03-21 18:05:35

+2

请参阅[此问题](http://stackoverflow.com/q/985281/501250)。如果你想要一个类似POSIX的分叉,那么使用Cygwin可能是你最好的选择。 – cdhowie 2013-03-21 18:06:10

回答

6

在Windows上,您不能使用fork()。改为使用CreateProcess()/CreateProcessEx()

+0

谢谢!我会仔细看看的。 – 2013-03-21 18:09:45

+4

CreateProcess等价于fork()+ exec()组合,而不是fork()。 – 2013-03-21 18:16:22