Last active
December 15, 2015 22:29
-
-
Save jonathanmarvens/5333216 to your computer and use it in GitHub Desktop.
C example of using `fork()`.
This file contains hidden or 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 <sys/types.h> | |
#include <unistd.h> | |
int var_global = 0; | |
int main() | |
{ | |
int var_local = 0; | |
pid_t process_id_child = fork(); | |
if ( process_id_child >= 0 ) | |
{ | |
if ( process_id_child == 0 ) | |
{ | |
var_global++; | |
var_local++; | |
puts( "Process [child]:" ); | |
printf( "\tvar_global => %2d\n", var_global ); | |
printf( "\tvar_local => %2d\n", var_local ); | |
puts( "" ); | |
} | |
else | |
{ | |
var_global = 20; | |
var_local = 10; | |
puts( "Process [parent]:" ); | |
printf( "\tvar_global => %2d\n", var_global ); | |
printf( "\tvar_local => %2d\n", var_local ); | |
puts( "" ); | |
} | |
} | |
else | |
{ | |
puts( "`fork(2)` failed. Exiting." ); | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment