In: Computer Science
Write a program in C or C++ that spawns three child processes. The first child sends a signal to the parent (you'll need the parent's pid!), which the parent shall catch. The second child waits for 10 seconds and then terminates. Once the parent detects that both of these has happened, it should signal the third child to terminate.
#include <stdio.h> /* printf */ #include <stdlib.h> /* exit */ #include <string.h> /* strcpy */ #include <unistd.h> /* sleep, fork */ #include <sys/shm.h> /* shmget, shmat, shmdt, shmctl */ #include <sys/wait.h> /* wait */ int main(void) { int pid1,pid2,pid3;
int shmid; /* return value from fork/shmget */ char *buffer; /* shared buffer */ key_t key = 123; /* arbitrary key */ shmid = shmget(key, 1024, 0600 | IPC_CREAT); buffer = (char *) shmat(shmid, NULL, 0); strcpy(buffer,""); pid1 = fork(); if (pid1 == 0) /* child */ { printf("child: putting message in buffer\n"); strcpy(buffer, "type any message here."); shmdt(buffer); /* detach memory from child process */ printf("child: sleeping for 5 seconds...\n"); sleep(5); printf("child: exiting\n"); exit(0); } else if (pid1 > 0) /* parent */ { printf("parent: waiting for child to exit...\n"); wait(NULL); printf("parent: message from child is %s\n", buffer); pid2 = fork(); if (pid2 == 0) /* 2nd child */ { printf(" second child: sleeping for 1o seconds...\n"); sleep(10); printf(" second child: exiting\n"); exit(0); } else { pid3 = fork(); if (pid3 == 0) /* 3rd child */ { printf("child 3: sleeping for 15 seconds...\n"); sleep(15); printf("child 3: exiting\n"); exit(0); } shmdt(buffer); /* detach memory from parent process */ shmctl(shmid, IPC_RMID, 0); /* delete memory block */ printf("parent: exiting\n"); } return 0; }