Dimaland

8

Dec 25th, 2023
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <string.h>
  6. #include <sys/wait.h>
  7. #include <signal.h>
  8. #include <time.h>
  9. #include <sys/time.h>
  10.  
  11. int usr1AmountSend = 0;
  12. int usr2AmountSend = 0;
  13. int usr1AmountAccept = 0;
  14. int usr2AmountAccept = 0;
  15. int currProc;
  16.  
  17. void termProc(int sig){
  18. printf("(%d) PID - %d (PPID - %d) finished work after %d signal SIGUSR1 and %d signal SIGUSR2\n",
  19. currProc, getpid(), getppid(), usr1AmountSend,
  20. usr2AmountSend);
  21.  
  22. for (;;) {
  23. pid_t childPid = wait(NULL);
  24. if (childPid == -1) {exit(EXIT_SUCCESS);}
  25. }
  26. }
  27.  
  28. void usr1Proc(int sig){usr1AmountAccept++;}
  29. void usr2Proc(int sig){usr2AmountAccept++;}
  30.  
  31. int main(){
  32. signal(SIGTERM, termProc);
  33. signal(SIGUSR1, usr1Proc);
  34. signal(SIGUSR2, usr2Proc);
  35.  
  36. currProc = 1; // process #1
  37. pid_t pid = fork(); // process #2
  38. if (pid == 0){
  39. currProc = 2; // process #2
  40. pid = fork(); // process #3
  41. if (pid == 0){
  42. currProc = 3; // process #3
  43. pid = fork(); // process #7
  44. if (pid == 0){currProc = 7;} // process #7
  45. } else {
  46. pid = fork(); // process #4
  47. if (pid == 0){
  48. currProc = 4; // process #4
  49. pid = fork(); // process #6
  50. if (pid == 0){currProc = 6;} // process #6
  51. } else {
  52. pid = fork(); // process #5
  53. if (pid == 0){
  54. currProc = 5; // process #5
  55. pid = fork(); // process #8
  56. if (pid == 0){currProc = 8;} // process #8
  57. }
  58. }
  59. }
  60. }
  61.  
  62. sleep(3);
  63.  
  64. for (int i = 0; i < 101; i++){
  65. if (currProc == 1 || currProc == 8)
  66. {
  67. usr2AmountSend++;
  68. kill(0, SIGUSR2);
  69. } else {
  70. usr1AmountSend++;
  71. kill(0, SIGUSR1);
  72. }
  73.  
  74. struct timeval currentTime;
  75. gettimeofday(&currentTime, NULL);
  76. char buffer[80];
  77. strftime(buffer, sizeof(buffer), "%H:%M:%S",
  78. localtime(&currentTime.tv_sec));
  79. sprintf(buffer, "%s.%06ld", buffer, currentTime.tv_usec);
  80.  
  81. printf("[%s] %d process (PID - %d|PPID - %d) send/accept USR1 (%d / %d) and USR2 (%d / %d)\n\n",
  82. buffer, currProc, getpid(), getppid(), usr1AmountSend, usr1AmountAccept, usr2AmountSend, usr2AmountAccept);
  83. }
  84. kill(0, SIGTERM);
  85.  
  86. return 0;
  87. }
  88.  
Advertisement
Add Comment
Please, Sign In to add comment