One of the major difficulties in porting programs from Unix to Windows is precisely in the process model of the two operating systems. Windows does not have the fork call.
Depending on how the fork is used in the program, it can be overridden by CreateProcess, trying to circumvent the differences of the two calls. In other cases, a Unix application that creates copies of itself can be modeled as a single multithreaded process in Windows with the CreateThread call.
An easier way would be to use the Cygwin library, which provides the functionality of the POSIX API with the cygwin1.dll DLL, including the fork call.
To use the library, simply perform the following steps:
Enter link and download the setup-x86.exe or setup -x86_64.exe depending on your system. Run the installer.
Click Next, and then choose install from the internet.
Set the directory to install Cygwin (best lets C: \ cygwin64).
Choose a directory to save the downloaded files.
Select a site to download.
When you get to the Select Packages option, type gcc and select gcc-core and gcc-g ++. The selection is made by clicking on top of the Skip, as shown in the figure:
AfterinstallingCygwinenterthefolderinwhichitwasinstalled,inmycaseC:\cygwin64\home\Sergioandputthecodeyouwanttocompilethere.OpenCygwinandcompiletheprogramnormallyusingtheforkcallwithgcc.
Hereisaverysimplecodeforanexampleofusingthefork:
#include<unistd.h>#include<stdio.h>intmain(intargc,char**argv){printf("Iniciando o programa\n");
int i, j, contador = 0;
pid_t pid = fork();
if(pid == 0){
for (i=0; i < 5; ++i)
printf("Processo filho: contador=%d\n", ++contador);
}
else if(pid > 0){
for (j=0; j < 5; ++j)
printf("Processo pai: contador=%d\n", ++contador);
}
else{
printf("fork() falhou!\n");
return 1;
}
printf("Programa terminou\n");
return 0;
}
In my case I compiled and executed like this:
gcc a.c -o hello
./hello
With Cygwin you can even mix calls on Unix with Windows calls, with some limitations. But remembering, the process model of the two operating systems is quite different, and so fork calls in Windows through Cygwin will be very slow!
I hope you have helped:)