Advertisement
jaimolias

Untitled

Mar 26th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <semaphore.h>
  4. #include <fcntl.h>
  5. #include <sys/stat.h>
  6. #include <sys/wait.h>
  7. #include <unistd.h>
  8. #include <time.h>
  9. #include <math.h>
  10. #define N_PROC 4
  11. #define SEM1 "/sem10"
  12.  
  13.  
  14. void manejador_SIGTERM_PADRE(int sig) {
  15. int i = 0;
  16. printf("FIN DE LA CARRERA\n");
  17. fflush(stdout);
  18. for (i = 0; i < N_PROC; i++)
  19.  
  20. wait(NULL);
  21.  
  22. exit(EXIT_SUCCESS);
  23. }
  24.  
  25. void manejador_SIGTERM_HIJO(int sig) {
  26.  
  27. exit(EXIT_SUCCESS);
  28. }
  29.  
  30. int main(void) {
  31. pid_t pid;
  32. int i, j;
  33. double num;
  34. sem_t *sem_1, *sem_2;
  35. FILE * f;
  36. int cont = 0;
  37. int id = 0;
  38. int cantidades[N_PROC];
  39. struct sigaction act;
  40. sigemptyset(&(act.sa_mask));
  41. act.sa_flags = 0;
  42.  
  43. act.sa_handler = manejador_SIGTERM_PADRE;
  44. if (sigaction(SIGTERM, &act, NULL) < 0) {
  45. perror("ERROR en el PADRE");
  46. exit(EXIT_FAILURE);
  47. }
  48. if ((sem_1 = sem_open(SEM1, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, 1)) == SEM_FAILED) {
  49. perror("sem_open");
  50. exit(EXIT_FAILURE);
  51. }
  52.  
  53. for (i = 0; i < N_PROC; i++)
  54. cantidades[i] = 0;
  55. for (i = 0; i < N_PROC; i++) {
  56. pid = fork();
  57. if (pid == 0) {
  58. act.sa_handler = manejador_SIGTERM_HIJO;
  59. if (sigaction(SIGTERM, &act, NULL) < 0) {
  60. perror("ERROR en el PADRE");
  61. exit(EXIT_FAILURE);
  62. }
  63. while (1) {
  64. f = fopen("fichero.txt", "a");
  65. sem_wait(sem_1);
  66. fprintf(f, "%d\n", i);
  67. srand((unsigned) time(NULL));
  68. num = rand() % 100000;
  69. fclose(f);
  70. usleep(num);
  71. sem_post(sem_1);
  72.  
  73. } }
  74. }
  75. if(pid>0) {
  76. while (1) {
  77. sem_wait(sem_2);
  78. f = fopen("fichero.txt", "r");
  79. while (fscanf(f, "%d", &id) == 1) {
  80.  
  81. cantidades[id]++;
  82. for (j = 0; j < N_PROC; j++) {
  83. printf("Cantidades del proceso %d que ha leido: %d \n", j, cantidades[j]);
  84. }
  85.  
  86. for (j = 0; j < N_PROC; j++) {
  87. if (cantidades[j] == 20) {
  88. printf("Ganador de la carrera: %d\n", j);
  89. remove("fichero.txt");
  90. kill(0, SIGTERM);
  91. }
  92. }
  93. }
  94.  
  95.  
  96. remove("fichero.txt");
  97. sleep(1);
  98. sem_post(sem_1);
  99.  
  100. }
  101. }
  102.  
  103.  
  104. sem_unlink(SEM1);
  105.  
  106. sem_close(sem_1);
  107.  
  108.  
  109. return 0;
  110. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement