Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Zmodyfikuj zadanie drugie tak, aby tworzony był jeden semafor o war- tości początkowej zero, a procesy potomne zwiększały go ojeden, w określonym porządku. Proces pierwszy bezwarunkowo zwiększy wartość semafora, proces drugi będzie czekał aż semafor będzie miał wartość dwa i zwiększy ją do trzech, itd. Wartość końcowa semafora powinna wynosić pięć.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/ipc.h>
- #include <sys/types.h>
- #include <sys/sem.h>
- #include <sys/wait.h>
- void sem_up(int semid)
- {
- struct sembuf up_operation = {0, 1, 0};
- if(semop(semid, &up_operation, 1) == -1){
- perror("semop");
- exit(EXIT_FAILURE);
- }
- }
- int main(void)
- {
- int semid;
- pid_t pid;
- if((semid = semget(IPC_PRIVATE, 1, 0775|IPC_CREAT|IPC_EXCL)) == -1){
- perror("semget");
- return EXIT_FAILURE;
- }
- if(semctl(semid, 0, SETVAL, 0) == -1){
- perror("setval_semctl");
- return EXIT_FAILURE;
- }
- printf("Stworzono semafor o wartosci poczatkowej 0\n");
- for(int i = 0; i < 5; i++){
- pid = fork();
- if(pid == -1){
- perror("fork");
- return EXIT_FAILURE;
- }
- else if(pid == 0){
- usleep(100000);
- sem_up(semid);
- int sem_value_buffer;
- if((sem_value_buffer = semctl(semid, 0, GETVAL)) == -1){
- perror("child_getval_semctl");
- return EXIT_FAILURE;
- }
- printf("Proces nr %d: Zwiekszona wartosc: %d\n", i+1, sem_value_buffer);
- }
- else{
- wait(0);
- int sem_value_buffer;
- if(i == 4){
- if((sem_value_buffer = semctl(semid, 0, GETVAL)) == -1){
- perror("parent_getval_semctl");
- return EXIT_FAILURE;
- }
- if(sem_value_buffer == 5){
- if(semctl(semid, 0, IPC_RMID) == -1){
- perror("rmid_semctl");
- return EXIT_FAILURE;
- }
- printf("Rodzic: Wartosc semafora rowna 5, usuwanie semafora...\n");
- }
- }
- return EXIT_SUCCESS;
- }
- }
- return EXIT_SUCCESS;
- }
Add Comment
Please, Sign In to add comment