//
// fork.c
//
// Created by SevenBits on 4/14/13.
//
// This demonstrates how to fork a process. Basically, what happens is, one
// process will fork itself, creating a cloned process. The return value of
// the fork() call can be used to direct one process to perform one task,
// and the clone to perform another! Inter-process communication is also
// possible.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main() {
printf("We're going to fork ourselves. This will spawn multiple processes,");
printf(" which will each count from 1 to 100 in a different process.\n");
pid_t pid = fork();
int i;
switch (pid) {
case -1:
printf("ERROR! Something went wrong!\n");
return 1;
break;
case 0:
for (i = 0; i < 100; i++) { // This runs in one process.
printf ("A: %d\n", i);
sleep(1);
}
break;
default: // This runs in another process (the parent).
for (i = 0; i < 100; i++) {
printf ("B: %d\n", i);
sleep(2);
}
break;
}
return 0;
}
I officially place this code in the public domain. Do whatever.
No comments:
Post a Comment