Here is a simple program which I am running trying to better understand the fork() call.
The output of this program is:Code:#include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> int main() { pid_t pid; //pid values of the parent and child process pid_t wpid; //return value from waitpid() char *message; int n; int stat; printf("fork program starting\n"); pid = fork(); if ( (pid=fork()) > 0) { //Parent Process if( (wpid = waitpid(pid, &stat, 0)) != pid) { fprintf(stderr, "Signal was received by parent while waiting...Error\n"); fprintf(stderr, "ERRNO: ", strerror(errno)); exit(1); } message = "This is the Parent process."; n = 3; } else if (pid == 0) { //Child Process message = "This is the Child process."; n =3; } else { //Error in Fork Call fprintf(stderr, "There was an error in the fork call\n"); fprintf(stderr, "ERRNO: %s\n", strerror(errno)); exit(1); } for(; n > 0; n--) { puts(message); sleep(1); } exit(0); }
My question is why when I have 'n=3' does each loop through 6 times?Code:corey@NuNn-Laptop:~/Desktop/Operating Systems/Test Programs$ ./fork fork program starting This is the Child process. This is the Child process. This is the Child process. This is the Child process. This is the Child process. This is the Child process. This is the Parent process. This is the Parent process. This is the Parent process. This is the Parent process. This is the Parent process. This is the Parent process.



LinkBack URL
About LinkBacks


