Skip to content

Instantly share code, notes, and snippets.

@spikegrobstein
Created November 25, 2011 05:12
Show Gist options
  • Save spikegrobstein/1392856 to your computer and use it in GitHub Desktop.
Save spikegrobstein/1392856 to your computer and use it in GitHub Desktop.
code for sam
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define DEFAULT_PROCESS_COUNT 4
int process_count = DEFAULT_PROCESS_COUNT;
void do_work(int pid);
int main(int argc, char **argv) {
if (argc > 1) {
process_count = atoi(argv[1]); // read the number of procs from commandline
}
printf("I'm starting up %d processes!\n", process_count);
int pid[process_count];
int i = 0;
int is_parent = 0;
for (i = 0; i < process_count; ++i) {
pid[i] = fork();
if (pid[i] != 0) {
printf("This is Worker i %d\n",i);
do_work(i);
exit(EXIT_SUCCESS);
break;
} else {
printf("This is Parent i %d\n",i);
is_parent = 1;
//printf("This is the Parent Process\n");
}
}
if (is_parent) {
for (i = 0; i < process_count; ++i) {
waitpid(pid[i], NULL, 0);
}
printf("Done!\n");
}
return 0;
}
void do_work(int pid) {
char cmd[1024];
sprintf(cmd, "echo 'hello world' >> %d_output.txt", pid);
system(cmd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment