Skip to content

Instantly share code, notes, and snippets.

@nb
Last active December 15, 2015 00:29
Show Gist options
  • Save nb/5173270 to your computer and use it in GitHub Desktop.
Save nb/5173270 to your computer and use it in GitHub Desktop.
#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
/* 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)/sizeof(int);
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) {
if (SEQ)
baba[i%s] = rand();
else
baba[rand()%s] = 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment