Advertisement
AJBF

ejercicio 10 Semaforo

May 4th, 2015
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.36 KB | None | 0 0
  1. #include <sys/shm.h>
  2. #include <unistd.h>
  3. #include <sys/stat.h>
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include <sys/types.h>
  7. #include <wait.h>
  8. #include <fcntl.h>
  9. #include<sys/ipc.h>
  10. #include <sys/sem.h>
  11. #include <string.h>
  12.  
  13. void P(int semid, int nsem)
  14. {
  15. struct sembuf buf;
  16. buf.sem_num = nsem;
  17. buf.sem_op = -1;
  18. buf.sem_flg = 0;
  19. semop(semid,&buf,1);
  20. }
  21.  
  22. void V(int semid, int nsem)
  23. {
  24. struct sembuf buf;
  25. buf.sem_num = nsem;
  26. buf.sem_op = 1;
  27. buf.sem_flg = 0;
  28. semop(semid,&buf,1);
  29. }
  30.  
  31. int crea_shm(key_t Clave, int cantby)
  32. {
  33. int shmid;
  34. shmid = shmget(Clave,cantby,IPC_CREAT | 0777);
  35. return shmid;
  36. }
  37.  
  38. int crea_sem(key_t Clave, int cantsem)
  39. {
  40. int semid ;
  41. semid = semget(Clave,cantsem,IPC_CREAT | 0777);
  42. return semid;
  43. }
  44.  
  45. int init_sem(int semid,int nsem,int valor)
  46. {
  47. int status;
  48. status = semctl(semid, nsem, SETVAL, valor);
  49. return status;
  50. }
  51.  
  52. main(int argc,char **argv)
  53. {
  54. int semid;
  55. int nsem = 2;
  56. int aux = 0;
  57. int maxNum;
  58. int pid1, pid2;
  59. int valor = 0;
  60. int status;
  61. key_t Clave;
  62.  
  63. printf("Ingrese el valor maximo: ");
  64. scanf("%d",&maxNum);
  65. semid = crea_sem(Clave,nsem);
  66. printf("%d\n", semid);
  67. if (semid == -1)
  68. perror("error semget\n")
  69. else
  70. perror("\n");
  71. status = init_sem(semid, 0, 1);
  72. status = init_sem(semid, 1, 0);
  73. if (status == -1)
  74. perror("error semctl\n")
  75. else
  76. perror("\n");
  77.  
  78.  
  79. Clave = ftok ("/bin/ls", 33);
  80. if (Clave == -1)
  81. {
  82. printf("Error, no se consigue la clave\n");
  83. exit(EXIT_FAILURE);
  84. }
  85.  
  86. printf("fin primera etapa\n");
  87. pid1 = fork();
  88.  
  89. if(pid1 == -1)
  90. {
  91. printf("ERROR\n");
  92. exit(EXIT_FAILURE);
  93. }
  94.  
  95. if (pid1 == 0)
  96. {
  97. aux++;
  98. while (aux <= maxNum)
  99. {
  100. P(semid, 0);
  101. aux++;
  102. if (aux <= maxNum)
  103. printf("%d\n", aux);
  104. aux++;
  105. V(semid, 1);
  106.  
  107. }
  108.  
  109. exit(EXIT_SUCCESS);
  110. }
  111. else
  112. {
  113. pid2 = fork();
  114. if(pid2 == -1)
  115. {
  116. printf("ERROR\n");
  117. exit(EXIT_FAILURE);
  118. }
  119.  
  120. if (pid2 == 0)
  121. {
  122. while (aux <= maxNum)
  123. {
  124. P(semid, 1);
  125. aux++;
  126. if (aux <= maxNum)
  127. printf("%d\n", aux);
  128. aux++;
  129. V(semid, 0);
  130. }
  131. }
  132. exit(EXIT_SUCCESS);
  133. }
  134. exit(EXIT_SUCCESS);
  135. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement