Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/shm.h>
- #include <unistd.h>
- #include <sys/stat.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <sys/types.h>
- #include <wait.h>
- #include <fcntl.h>
- #include<sys/ipc.h>
- #include <sys/sem.h>
- #include <string.h>
- void P(int semid, int nsem)
- {
- struct sembuf buf;
- buf.sem_num = nsem;
- buf.sem_op = -1;
- buf.sem_flg = 0;
- semop(semid,&buf,1);
- }
- void V(int semid, int nsem)
- {
- struct sembuf buf;
- buf.sem_num = nsem;
- buf.sem_op = 1;
- buf.sem_flg = 0;
- semop(semid,&buf,1);
- }
- int crea_shm(key_t Clave, int cantby)
- {
- int shmid;
- shmid = shmget(Clave,cantby,IPC_CREAT | 0777);
- return shmid;
- }
- int crea_sem(key_t Clave, int cantsem)
- {
- int semid ;
- semid = semget(Clave,cantsem,IPC_CREAT | 0777);
- return semid;
- }
- int init_sem(int semid,int nsem,int valor)
- {
- int status;
- status = semctl(semid, nsem, SETVAL, valor);
- return status;
- }
- main(int argc,char **argv)
- {
- int semid;
- int nsem = 2;
- int aux = 0;
- int maxNum;
- int pid1, pid2;
- int valor = 0;
- int status;
- key_t Clave;
- printf("Ingrese el valor maximo: ");
- scanf("%d",&maxNum);
- semid = crea_sem(Clave,nsem);
- printf("%d\n", semid);
- if (semid == -1)
- perror("error semget\n")
- else
- perror("\n");
- status = init_sem(semid, 0, 1);
- status = init_sem(semid, 1, 0);
- if (status == -1)
- perror("error semctl\n")
- else
- perror("\n");
- Clave = ftok ("/bin/ls", 33);
- if (Clave == -1)
- {
- printf("Error, no se consigue la clave\n");
- exit(EXIT_FAILURE);
- }
- printf("fin primera etapa\n");
- pid1 = fork();
- if(pid1 == -1)
- {
- printf("ERROR\n");
- exit(EXIT_FAILURE);
- }
- if (pid1 == 0)
- {
- aux++;
- while (aux <= maxNum)
- {
- P(semid, 0);
- aux++;
- if (aux <= maxNum)
- printf("%d\n", aux);
- aux++;
- V(semid, 1);
- }
- exit(EXIT_SUCCESS);
- }
- else
- {
- pid2 = fork();
- if(pid2 == -1)
- {
- printf("ERROR\n");
- exit(EXIT_FAILURE);
- }
- if (pid2 == 0)
- {
- while (aux <= maxNum)
- {
- P(semid, 1);
- aux++;
- if (aux <= maxNum)
- printf("%d\n", aux);
- aux++;
- V(semid, 0);
- }
- }
- exit(EXIT_SUCCESS);
- }
- exit(EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement