1.

Solve : How to program a fork() equivalent in Windows C??

Answer»

Hi all,

I've found some stuff on the web about Windows doesn't support fork() and some people say use spawn() but I can't see a clear example of how to do it.

Here's what I'm TRYING to code with the fork() call. Can anyone suggest how I'd substitute spawn so I can execv the 3rd-party executable SYNCHRONOUSLY and get its return code?
Code: [Select]#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

main(int argc, CHAR *ARGV[])

{
FILE *fp;
int pid, status, died, i;
time_t now;

fp = fopen("C:\\path\\to\\cmdlog.txt","a+");
time(&now);
FPRINTF(fp,"Started %s%s", ctime(&now), argv[0]);
for(i=1;i<argc;i++)
fprintf(fp," %s", argv[i]);
fprintf(fp,"\n");
fclose(fp);

// pid=fork();
argv[0] = "C:\\path\\to\\original-command.exe";
execv("C:\\path\\to\\original-command", argv);
// died = wait(&status);

fp = fopen("C:\\path\\to\\cmdlog.txt","a+");
time(&now);
fprintf(fp, "Completed %s\n", ctime(&now));
fclose(fp);

// return status;
return 0;
}I've finally cracked it.

The following official article from Microsoft was way over complicated and I couldn't understand it
http://support.microsoft.com/kb/190351

but luckily I found this article which explains it in simple terms
http://www.cprogramming.com/faq/cgi-bin/smartfaq.cgi?answer=1044654269&id=1043284392

The solution is really simple
Code: [Select]#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <process.h>

main(int argc, char *argv[])

{
FILE *fp;
int pid, status, died, i;
time_t now;

fp = fopen("C:\\path\\to\\cmdlog.txt","a+");
time(&now);
fprintf(fp,"Started %s%s", ctime(&now), argv[0]);
for(i=1;i<argc;i++)
fprintf(fp," %s", argv[i]);
fprintf(fp,"\n");
fclose(fp);

argv[0] = "C:\\path\\to\\original-command.exe";
status = spawnv(P_WAIT, "C:\\path\\to\\original-command.exe", argv);

fp = fopen("C:\\path\\to\\cmdlog.txt","a+");
time(&now);
fprintf(fp, "Completed %s\n", ctime(&now));
fclose(fp);

return status;
}



Discussion

No Comment Found