Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include<sys/types.h>
- #include<unistd.h>
- #include<signal.h>
- #include<fcntl.h>
- #include<sys/wait.h>
- int counter = 0;
- int fd;
- const char* filename;
- int j = 0;
- int no_of_children;
- int* cpid;
- //User define signal handler
- static void sig_usr1(int);
- static void sig_usr2(int);
- static void sig_usr1(int signo)
- {
- //Now the child process waits for reading the Filename
- //Block SIGUSR1 until it's complete
- signal(SIGUSR1, SIG_IGN);
- printf("Blocked now.\n");
- printf("Child no %d is reading now.\n\n",getpid());
- fd = open(filename, O_RDONLY | O_CREAT);
- char buf = 'a';
- int k=0;
- char* op = (char*) malloc (255*sizeof(char));
- while(read (fd, &buf, 1))
- {
- if (buf == '\n')
- {
- op[k] = '\0';
- break;
- }
- else
- {
- op[k++] = buf;
- }
- }
- //Now wait for a second and then send a signal
- sleep(1);
- //Print the contents of the buffer via op
- printf("Output: %s\n\n", op);
- //Now unblock the signal
- kill(getppid(), SIGUSR2);
- signal(SIGUSR1, sig_usr1);
- printf("Unblocked now\n");
- }
- static void sig_usr2(int signo)
- {
- if (signo == SIGUSR2)
- {
- printf("Parent Received SIGUSR2. Child Process with PID %d is now free\n", cpid[j]);
- kill (cpid[j++], SIGUSR1);
- if (j == no_of_children)
- {
- j = 0;
- }
- }
- }
- int main(int argc, char* argv[])
- {
- //Filename is the first argument
- filename = argv[1];
- //Number of Child Processes to be spawned
- no_of_children = atoi(argv[2]);
- cpid = (int*) malloc (no_of_children*sizeof(int));
- signal(SIGUSR2, sig_usr2);
- //Create no_of_children children
- for(int i=0; i<no_of_children; i++)
- {
- cpid[i] = fork();
- if (cpid[i] == 0)
- {
- //Inside a child
- printf("Created %dth child process", i);
- printf(" with Process ID = %d\n", getpid());
- signal(SIGUSR1, sig_usr1);
- while(1)
- {
- pause();
- }
- //Every child process must exit so control goes back to the parent
- exit(0);
- }
- }
- //Returns to the parent process
- while(1)
- {
- int fpid = cpid[j];
- //Send the signal to the free child process
- //printf("Sending to PID %d\n", fpid);
- kill(fpid, SIGUSR1);
- //j = (j < no_of_children - 1) ? j + 1 : 0;
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment