//forkExample.c //John T. Rine //October 23, 2011 #include #include #include #define CHILD 0 int globalTestVar = 0; char *child(int *); char *parent(); char *error(); int main(int argc, char **argv) { char * procID = '\0'; int localTestVar = 0; int *localTestVarPTR = NULL; localTestVarPTR = &localTestVar; pid_t pid; printf("Enter a global variable value\n"); scanf("%d", &globalTestVar); printf("Enter a local variable value\n"); scanf("%d", &localTestVar); pid = fork(); //Error, failed to fork if (pid < CHILD) procID = error(); //child else if (pid == CHILD) procID = child(localTestVarPTR); //parent else procID = parent(); //Executed by both parent and child. printf("procID = %s\n", procID); printf("Global variable = %d\n", globalTestVar); printf("Local variable = %d\n", localTestVar); } char *child(int *localTestVarPtr) { char *procID; procID = "Child Process: "; ++*localTestVarPtr; ++globalTestVar; return procID; } char *parent() { char *procID; procID = "Parent Process:"; return procID; } char *error() { char *procID; procID = "Failed to fork"; return procID; }