96 lines
2.9 KiB
C
96 lines
2.9 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* semaphore_basics.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: ruiferna <ruiferna@student.42porto.com> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2025/10/14 18:59:45 by ruiferna #+# #+# */
|
|
/* Updated: 2025/10/14 20:34:46 by ruiferna ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <unistd.h>
|
|
#include <sys/wait.h>
|
|
#include <semaphore.h>
|
|
#include <fcntl.h>
|
|
|
|
#define NUM_CHILDREN 5
|
|
#define NUM_RESOURCES 3
|
|
#define SEM_NAME "/philo_sem"
|
|
|
|
int main(int argc, char *argv[]) {
|
|
sem_t *sem;
|
|
pid_t pids[NUM_CHILDREN];
|
|
int i;
|
|
|
|
(void) argc;
|
|
(void) argv;
|
|
// Remove semaphore if it exists from previous run
|
|
sem_unlink(SEM_NAME);
|
|
|
|
// Create semaphore with 3 resources
|
|
sem = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0644, NUM_RESOURCES);
|
|
if (sem == SEM_FAILED) {
|
|
printf("Error creating semaphore\n");
|
|
return 1;
|
|
}
|
|
|
|
i = 0;
|
|
while (i < NUM_CHILDREN)
|
|
{
|
|
pids[i] = fork();
|
|
if (pids[i] == -1) {
|
|
printf("Error creating process\n");
|
|
return 1;
|
|
}
|
|
if (pids[i] == 0) {
|
|
// Child process
|
|
int child_id = i + 1;
|
|
sem_t *child_sem;
|
|
|
|
// Open semaphore in child process
|
|
child_sem = sem_open(SEM_NAME, 0);
|
|
if (child_sem == SEM_FAILED) {
|
|
printf("Child %d: Error opening semaphore\n", child_id);
|
|
exit(1);
|
|
}
|
|
|
|
printf("Child %d (PID: %d): Waiting for resource...\n", child_id, getpid());
|
|
|
|
// Acquire resource
|
|
sem_wait(child_sem);
|
|
printf("Child %d (PID: %d): Acquired resource\n", child_id, getpid());
|
|
|
|
// Use resource for 500ms
|
|
printf("Child %d (PID: %d): Using resource...\n", child_id, getpid());
|
|
usleep(500000);
|
|
|
|
// Release resource
|
|
printf("Child %d (PID: %d): Released resource\n", child_id, getpid());
|
|
sem_post(child_sem);
|
|
|
|
sem_close(child_sem);
|
|
exit(0);
|
|
}
|
|
i++;
|
|
}
|
|
|
|
// Use waitpid() to wait for all children to finish
|
|
i = 0;
|
|
while (i < NUM_CHILDREN)
|
|
{
|
|
waitpid(pids[i], NULL, 0);
|
|
i++;
|
|
}
|
|
|
|
// Clean semaphone
|
|
sem_close(sem);
|
|
sem_unlink(SEM_NAME);
|
|
|
|
return (0);
|
|
}
|
|
|