Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <semaphore.h>
- #include <fcntl.h>
- #include <sys/stat.h>
- #include <sys/wait.h>
- #include <unistd.h>
- #include <time.h>
- #include <math.h>
- #define N_PROC 4
- #define SEM1 "/sem10"
- void manejador_SIGTERM_PADRE(int sig) {
- int i = 0;
- printf("FIN DE LA CARRERA\n");
- fflush(stdout);
- for (i = 0; i < N_PROC; i++)
- wait(NULL);
- exit(EXIT_SUCCESS);
- }
- void manejador_SIGTERM_HIJO(int sig) {
- exit(EXIT_SUCCESS);
- }
- int main(void) {
- pid_t pid;
- int i, j;
- double num;
- sem_t *sem_1, *sem_2;
- FILE * f;
- int cont = 0;
- int id = 0;
- int cantidades[N_PROC];
- struct sigaction act;
- sigemptyset(&(act.sa_mask));
- act.sa_flags = 0;
- act.sa_handler = manejador_SIGTERM_PADRE;
- if (sigaction(SIGTERM, &act, NULL) < 0) {
- perror("ERROR en el PADRE");
- exit(EXIT_FAILURE);
- }
- if ((sem_1 = sem_open(SEM1, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, 1)) == SEM_FAILED) {
- perror("sem_open");
- exit(EXIT_FAILURE);
- }
- for (i = 0; i < N_PROC; i++)
- cantidades[i] = 0;
- for (i = 0; i < N_PROC; i++) {
- pid = fork();
- if (pid == 0) {
- act.sa_handler = manejador_SIGTERM_HIJO;
- if (sigaction(SIGTERM, &act, NULL) < 0) {
- perror("ERROR en el PADRE");
- exit(EXIT_FAILURE);
- }
- while (1) {
- f = fopen("fichero.txt", "a");
- sem_wait(sem_1);
- fprintf(f, "%d\n", i);
- srand((unsigned) time(NULL));
- num = rand() % 100000;
- fclose(f);
- usleep(num);
- sem_post(sem_1);
- } }
- }
- if(pid>0) {
- while (1) {
- sem_wait(sem_2);
- f = fopen("fichero.txt", "r");
- while (fscanf(f, "%d", &id) == 1) {
- cantidades[id]++;
- for (j = 0; j < N_PROC; j++) {
- printf("Cantidades del proceso %d que ha leido: %d \n", j, cantidades[j]);
- }
- for (j = 0; j < N_PROC; j++) {
- if (cantidades[j] == 20) {
- printf("Ganador de la carrera: %d\n", j);
- remove("fichero.txt");
- kill(0, SIGTERM);
- }
- }
- }
- remove("fichero.txt");
- sleep(1);
- sem_post(sem_1);
- }
- }
- sem_unlink(SEM1);
- sem_close(sem_1);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement