Tobiahao

S01_SEMAFORY_07

Dec 17th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.80 KB | None | 0 0
  1. /*
  2. Zademonstruj działanie operacji SETALL, GETALL, IPC_STAT, GETPID, GETZCNT.
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <sys/ipc.h>
  8. #include <sys/types.h>
  9. #include <sys/sem.h>
  10. #include <time.h>
  11.  
  12. #define NUMBER_OF_SEMAPHORES 4
  13.  
  14. int main(void)
  15. {
  16.     srand(time(NULL));
  17.  
  18.     int semid;
  19.     union semun arg;
  20.     u_short *array_buffer;
  21.     struct semid_ds buffer;
  22.     pid_t pid;
  23.     short semnum;
  24.  
  25.     arg.array = (u_short *)calloc(NUMBER_OF_SEMAPHORES, sizeof(u_short));
  26.     array_buffer = (u_short *)calloc(NUMBER_OF_SEMAPHORES, sizeof(u_short));
  27.  
  28.     if((semid = semget(IPC_PRIVATE, NUMBER_OF_SEMAPHORES, 0775 | IPC_CREAT | IPC_EXCL)) == -1){
  29.         perror("semget");
  30.         return EXIT_FAILURE;
  31.     }
  32.  
  33.     /* SETALL */
  34.     for(int i = 0; i < NUMBER_OF_SEMAPHORES; i++)
  35.         arg.array[i] = rand() % 10;
  36.  
  37.     if(semctl(semid, 0, SETALL, arg.array) == -1){
  38.         perror("setall_semctl");
  39.         return EXIT_FAILURE;
  40.     }
  41.  
  42.     /* GETALL */
  43.     if(semctl(semid, 0, GETALL, array_buffer) == -1){
  44.         perror("getall_semctl");
  45.         return EXIT_FAILURE;
  46.     }
  47.     printf("Wartosci semaforow: ");
  48.     for(int i = 0; i < NUMBER_OF_SEMAPHORES; i++)
  49.         printf("%hu ", array_buffer[i]);
  50.     printf("\n");
  51.  
  52.     /* IPC_STAT */ 
  53.     if(semctl(semid, 0, IPC_STAT, &buffer) == -1){
  54.         perror("ipc_stat_semctl");
  55.         return EXIT_FAILURE;
  56.     }
  57.     printf("Liczba semaforow: %hu\n", buffer.sem_nsems);
  58.  
  59.     /* GETPID */
  60.     if(semctl(semid, 0, GETPID, &pid) == -1){
  61.         perror("pid_semctl");
  62.         return EXIT_FAILURE;
  63.     }
  64.     printf("Pid procesu, ktory ostatnio wykonywal operacje na semaforach: %d\n", pid);
  65.  
  66.     /* GETZCNT */
  67.     if((semnum = semctl(semid, 0, GETZCNT)) == -1){
  68.         perror("getzcnt_semctl");
  69.         return EXIT_FAILURE;
  70.     }
  71.     printf("Ilosc czekajacych procesow: %hu\n", semnum);
  72.  
  73.     if(semctl(semid, 0, IPC_RMID) == -1){
  74.         perror("ipc_rmid_semctl");
  75.         return EXIT_FAILURE;
  76.     }
  77.  
  78.     return EXIT_SUCCESS;
  79. }
Add Comment
Please, Sign In to add comment