Skip to content

Instantly share code, notes, and snippets.

@vanangamudi
Created August 29, 2014 13:20
Show Gist options
  • Save vanangamudi/2127af5883d655ab533d to your computer and use it in GitHub Desktop.
Save vanangamudi/2127af5883d655ab533d to your computer and use it in GitHub Desktop.
no name
#include "stdio.h"
#include "unistd.h"
#define MSGLEN 32
int main (int argc, char const* argv[])
{
// check for arguments
if(argc < 2){
printf("\n\n[Error] : ***Usage : ./main.exe <no_of_levels>***\n\n");
return -1;
}
// get depth and immediate children from cmdline args
int im_children_count = 2;
int depth = atoi(argv[1]);
pid_t id;
pid_t *pid_array = (pid_t*)malloc(sizeof(*pid_array) * depth);
printf("\nROOT : %d\n",getpid());
fflush(stdout);
int root = 0;
int pipefd[2];
int retval;
int msg[MSGLEN];
while( depth-- > 0){
retval = pipe(pipefd);
if (retval < 0)
perror("pipe"), exit(1);
int i;
for(i=0;i<im_children_count;i++){
retval = fork();
if( id == 0) {
root = 1;
break;
}
pid_array[i] = retval;
}
if( i >= im_children_count)
break;
printf("\n>> PID : %d : PPID : %d", getpid(), getppid());
fflush(stdout);
}
if (root == 0) {
int i;
for (i =0; i< im_children_count - 1; i++)
write(pipefd[1], &pid_array[i], sizeof(pid_array[i]) ) ;
printf("%d << PPID : %d", getpid(), getppid());
fflush(stdout);
i++;
write(pipefd[1], &pid_array[i], sizeof(pid_array[i]) ) ;
int status;
for (i =0; i< im_children_count - 1; i++)
waitpid(pid_array[i], &status, NULL);
} else {
while(1) {
retval = 0;
read(pipefd[0], &retval, sizeof(*pid_array));
if (retval == getpid()) {
printf("%d: i got my chance", retval);
int i;
for (i =0; i < im_children_count - 1; i++)
write(pipefd[1], &pid_array[i], sizeof(pid_array[i]) ) ;
printf(">> %d << PPID : %d", getpid(), getppid());
fflush(stdout);
i++;
write(pipefd[1], &pid_array[i], sizeof(pid_array[i]) ) ;
break;
}
}
}
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment