Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h> //printf, perror
- #include <stdlib.h> //EXIT_FAILURE, EXIT_SUCCESS
- #include <string.h> //sprintf
- #include <unistd.h> //open, close, read, write
- #include <fcntl.h> //flags: O_CREAT, O_EXCL
- #include <semaphore.h> //sem_open, sem_wait, sem_post, sem_close
- #define SEMAPHORE_NAME "/global_counter" //name of semaphore
- sem_t *semaphore = NULL;
- //pointer to semaphore
- const int PERM = 0600;
- //Permission to the semaphore
- void create_semaphore()
- {
- semaphore = sem_open(SEMAPHORE_NAME, O_CREAT, PERM, 1);
- if (semaphore == SEM_FAILED)
- {
- perror("Error when creating the semaphore ...\n");
- exit(EXIT_FAILURE);
- }
- }
- void delete_semaphore()
- {
- if (sem_close(semaphore) == -1)
- {
- perror("Error can't close semaphore ...\n");
- exit(EXIT_FAILURE);
- }
- if (sem_unlink(SEMAPHORE_NAME) == -1)
- {
- perror("Error can't delete (unlink) semaphore ...\n");
- exit(EXIT_FAILURE);
- }
- }
- int main()
- {
- //TODO: Create or use the existing semaphore.
- create_semaphore();
- //Main task: Loop 2000000 times and add 1 to the counter inside the loop
- for (int i = 0; i < 200000; ++i)
- {
- //TODO: You have to place the P/V operations here...
- // But remember, the Linux API does not provide P/V directly.
- sem_wait(semaphore);
- //Open the file
- int file = open("counter", O_RDWR);
- if (file == -1)
- {
- printf("Could not open file, exiting!\n");
- exit(EXIT_FAILURE);
- }
- //Read the number
- const int MAX_LEN = 64;
- char number[MAX_LEN];
- read(file, &number, sizeof(number));
- //Convert the string into an integer
- int counter = atoi(number);
- counter++;
- //Write the new number into the counter
- sprintf(number, "%d\n", counter);
- lseek(file, 0, 0);
- write(file, &number, strlen(number) + 1);
- //Close the file
- close(file);
- sem_post(semaphore);
- }
- delete_semaphore();
- printf("Finished!\n");
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement