Minimal Linux and Windows process spawn test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#ifdef _WIN32 | |
#include <process.h> /* Required for _spawnv */ | |
#include <windows.h> | |
/* We make getpid() work in a similar | |
way on Windows as it does on Linux */ | |
#define getpid() GetCurrentProcessId() | |
#endif | |
#ifdef __linux__ | |
#include <unistd.h> | |
#endif | |
void spawn_new_process(char * const *argv); | |
int pid; | |
int main(int argc, char *argv[]) | |
{ | |
pid = getpid(); | |
if(argc > 1 && strcmp(argv[1],"the_new_process") == 0) | |
{ | |
printf("[%d] This is a new process, and not a fork.\n", pid); | |
} | |
else | |
{ | |
printf("[%d] This is the original process.\n", pid); | |
char *new_args[2]; | |
new_args[0] = argv[0]; | |
new_args[1] = "the_new_process"; | |
spawn_new_process((char * const *)new_args); | |
} | |
return(0); | |
} | |
void spawn_new_process(char * const *argv) | |
{ | |
#ifdef _WIN32 | |
/* This code block will also be reached on a | |
64 bit version of a Windows desktop OS */ | |
_spawnv(_P_NOWAIT, argv[0], (const char * const *)argv); | |
#endif | |
#ifdef __linux__ | |
pid = getpid(); | |
/* Create copy of current process */ | |
pid = fork(); | |
/* The parent`s new pid will be 0 */ | |
if(pid != 0) | |
{ | |
/* We are now in a child progress | |
Execute different process */ | |
printf("[%d] Child (fork) process will call exec.\n", | |
pid); | |
execv(argv[0], argv); | |
/* This code will never be executed */ | |
printf("[%d] Child (fork) process is exiting.\n", pid); | |
exit(EXIT_SUCCESS); | |
} | |
#endif | |
/* We are still in the original process */ | |
printf("[%d] Original process is exiting.\n", pid); | |
exit(EXIT_SUCCESS); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment