Created
August 23, 2017 03:11
-
-
Save hawkingrei/4664069fad296bb17d8c845f5696ff7c to your computer and use it in GitHub Desktop.
fork in linux example
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 <unistd.h> | |
| int main(int argc, char **argv) | |
| { | |
| printf("--beginning of program\n"); | |
| int counter = 0; | |
| pid_t pid = fork(); | |
| if (pid == 0) | |
| { | |
| // child process | |
| int i = 0; | |
| for (; i < 5; ++i) | |
| { | |
| printf("child process: counter=%d\n", ++counter); | |
| } | |
| } | |
| else if (pid > 0) | |
| { | |
| // parent process | |
| int j = 0; | |
| for (; j < 5; ++j) | |
| { | |
| printf("parent process: counter=%d\n", ++counter); | |
| } | |
| } | |
| else | |
| { | |
| // fork failed | |
| printf("fork() failed!\n"); | |
| return 1; | |
| } | |
| printf("--end of program--\n"); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment