Created
November 25, 2011 05:12
-
-
Save spikegrobstein/1392856 to your computer and use it in GitHub Desktop.
code for sam
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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