Skip to content

Instantly share code, notes, and snippets.

@RyosukeMiyahara
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyosukeMiyahara/ee829284a4caef4c932e to your computer and use it in GitHub Desktop.
Save RyosukeMiyahara/ee829284a4caef4c932e to your computer and use it in GitHub Desktop.
fork() usage
#include <iostream> // cout, endl
#include <unistd.h> // getpid()
#include <stdlib.h> // exit()
int main(void) {
std::cout << "(First) Process ID is " << getpid() << std::endl;
// Create child process
int forkReturnValue = fork(); // --- Process forks here! ---
if (forkReturnValue == 0) {
// Child process receives 0 as a return value of fork()
std::cout << "Created process ID is " << getpid() << std::endl;
std::cout << "Parent process ID of created process is " << getppid() << std::endl;
exit(0);
}
// Parent process receives child process ID as a return value of fork()
std::cout << "Child process ID is " << forkReturnValue << std::endl;
// Of course. process id is not changed from first getpid()
std::cout << "(Second) Process ID is " << getpid() << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment