Advertisement
Guest User

Untitled

a guest
Nov 15th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.15 KB | None | 0 0
  1. #include <stdio.h>     //printf, perror
  2. #include <stdlib.h>    //EXIT_FAILURE, EXIT_SUCCESS
  3. #include <string.h>    //sprintf
  4. #include <unistd.h>    //open, close, read, write
  5. #include <fcntl.h>     //flags: O_CREAT, O_EXCL
  6. #include <semaphore.h> //sem_open, sem_wait, sem_post, sem_close
  7.  
  8. #define SEMAPHORE_NAME "/global_counter" //name of semaphore
  9. sem_t *semaphore = NULL;
  10. //pointer to semaphore
  11. const int PERM = 0600;
  12. //Permission to the semaphore
  13.  
  14. void create_semaphore()
  15. {
  16.     semaphore = sem_open(SEMAPHORE_NAME, O_CREAT, PERM, 1);
  17.     if (semaphore == SEM_FAILED)
  18.     {
  19.         perror("Error when creating the semaphore ...\n");
  20.         exit(EXIT_FAILURE);
  21.     }
  22. }
  23.  
  24. void delete_semaphore()
  25. {
  26.     if (sem_close(semaphore) == -1)
  27.     {
  28.         perror("Error can't close semaphore ...\n");
  29.         exit(EXIT_FAILURE);
  30.     }
  31.     if (sem_unlink(SEMAPHORE_NAME) == -1)
  32.     {
  33.         perror("Error can't delete (unlink) semaphore ...\n");
  34.         exit(EXIT_FAILURE);
  35.     }
  36. }
  37.  
  38. int main()
  39. {
  40.     //TODO: Create or use the existing semaphore.
  41.     create_semaphore();
  42.  
  43.     //Main task: Loop 2000000 times and add 1 to the counter inside the loop
  44.     for (int i = 0; i < 200000; ++i)
  45.     {
  46.         //TODO: You have to place the P/V operations here...
  47.         //      But remember, the Linux API does not provide P/V directly.
  48.         sem_wait(semaphore);
  49.  
  50.         //Open the file
  51.         int file = open("counter", O_RDWR);
  52.         if (file == -1)
  53.         {
  54.             printf("Could not open file, exiting!\n");
  55.             exit(EXIT_FAILURE);
  56.         }
  57.  
  58.         //Read the number
  59.         const int MAX_LEN = 64;
  60.         char number[MAX_LEN];
  61.         read(file, &number, sizeof(number));
  62.  
  63.         //Convert the string into an integer
  64.         int counter = atoi(number);
  65.         counter++;
  66.  
  67.         //Write the new number into the counter
  68.         sprintf(number, "%d\n", counter);
  69.         lseek(file, 0, 0);
  70.         write(file, &number, strlen(number) + 1);
  71.  
  72.         //Close the file
  73.         close(file);
  74.  
  75.         sem_post(semaphore);
  76.     }
  77.  
  78.     delete_semaphore();
  79.  
  80.     printf("Finished!\n");
  81.  
  82.     return EXIT_SUCCESS;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement