Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2020
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1.  
  2.  
  3. Please find the complete program for the question below.
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <errno.h>
  9. #include <unistd.h> /* psignal */
  10. #include <sys/types.h> /* waitpid */
  11. #include <sys/wait.h> /* waitpid */
  12.  
  13. #define N 2
  14.  
  15. int main() {
  16.  
  17. int status, i;
  18. pid_t pid[N], retpid;
  19.  
  20. /* Parent creates N children */
  21. for(i = 0; i < N; i++) {
  22. if((pid[i] = fork()) == 0) { /* child */
  23. strcpy("Hello", "World"); /* Writing on read-only location. It creates SIGSEGV */
  24. exit(100 + i);
  25. }
  26. }
  27.  
  28. /* Parent reaps N children in order */
  29. i = 0;
  30. while ((retpid = waitpid(pid[i++], &status, 0)) > 0) {
  31. if(WIFEXITED(status))
  32. printf("child %d terminated normally with exit status=%d\n", retpid, WEXITSTATUS(status));
  33. else if(WIFSIGNALED(status)) { /* Exited with a signal */
  34. printf("child %d terminated by signal %d: \n", retpid, SIGSEGV);
  35. psignal(WTERMSIG(status), NULL);
  36. }
  37. else
  38. printf("child %d terminated abnormally \n", retpid);
  39. }
  40.  
  41. /* The only normal termination is if there are no more children */
  42. if(errno != ECHILD)
  43. printf("waitpid error");
  44.  
  45. exit(0);
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement