Skip to content

Instantly share code, notes, and snippets.

@nb
Last active December 15, 2015 00:29

Revisions

  1. nb revised this gist Mar 15, 2013. 1 changed file with 9 additions and 4 deletions.
    13 changes: 9 additions & 4 deletions fork.c
    Original file line number Diff line number Diff line change
    @@ -9,13 +9,16 @@
    #define FORKS 50
    /* How many random elements to change in the child process */
    #define NUMRANDS 100000
    /* Change sequential or random elements in the child process */
    #define SEQ 0


    int main() {
    int forks = 100;
    int i, j;
    int *baba;
    int f;
    int s = MB*1024*1024;
    int s = (MB*1024*1024)/sizeof(int);
    baba = malloc(s*sizeof(int));
    printf("Start loop in parent\n");
    for(i=0; i<s; ++i) {
    @@ -28,8 +31,10 @@ int main() {
    if (0 == f) {
    printf("Start loop in child %d\n", getpid());
    for(i=0; i<NUMRANDS; ++i) {
    baba[rand()%s] = rand();
    //baba[i] = rand();
    if (SEQ)
    baba[i%s] = rand();
    else
    baba[rand()%s] = rand();
    }
    printf("End loop in child %d\n", getpid());
    exit(0);
    @@ -53,4 +58,4 @@ int main() {
    }
    }
    free(baba);
    }
    }
  2. nb created this gist Mar 15, 2013.
    56 changes: 56 additions & 0 deletions fork.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    #include <unistd.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <errno.h>

    /* MB of memory to allocate */
    #define MB 100
    /* How many processes to spawn */
    #define FORKS 50
    /* How many random elements to change in the child process */
    #define NUMRANDS 100000

    int main() {
    int forks = 100;
    int i, j;
    int *baba;
    int f;
    int s = MB*1024*1024;
    baba = malloc(s*sizeof(int));
    printf("Start loop in parent\n");
    for(i=0; i<s; ++i) {
    baba[i] = rand();
    }
    printf("End loop in child\n");
    forks = FORKS;
    while(forks--) {
    f = fork();
    if (0 == f) {
    printf("Start loop in child %d\n", getpid());
    for(i=0; i<NUMRANDS; ++i) {
    baba[rand()%s] = rand();
    //baba[i] = rand();
    }
    printf("End loop in child %d\n", getpid());
    exit(0);
    } else if ( -1 == f) {
    printf("Error forking #%d\n", forks);
    } else {
    printf("Forked %d\n", forks);
    }
    }

    while (1) {
    int status;
    pid_t done = wait(&status);
    if (done == -1) {
    if (errno == ECHILD) break; // no more child processes
    } else {
    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
    printf("Failed wait: %d\n", done);
    exit(1);
    }
    }
    }
    free(baba);
    }