diff --git a/rendu/semaphore_basics.c b/rendu/semaphore_basics.c new file mode 100644 index 0000000..768cc4c --- /dev/null +++ b/rendu/semaphore_basics.c @@ -0,0 +1,95 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* semaphore_basics.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: ruiferna +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2025/10/14 18:59:45 by ruiferna #+# #+# */ +/* Updated: 2025/10/14 20:34:46 by ruiferna ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include +#include +#include +#include +#include +#include + +#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); +} + diff --git a/testers/test_13_semaphore_basics.sh b/testers/test_13_semaphore_basics.sh index b5d7c0d..df0a922 100755 --- a/testers/test_13_semaphore_basics.sh +++ b/testers/test_13_semaphore_basics.sh @@ -133,7 +133,7 @@ echo -n "Test 6: No zombie processes... " "$EXE_PATH" > /dev/null 2>&1 & PARENT_PID=$! sleep 1 -ZOMBIE_COUNT=$(ps aux | grep "$PARENT_PID" | grep -c "defunct" || echo "0") +ZOMBIE_COUNT=$(ps aux | grep "$PARENT_PID" | grep "defunct" | wc -l) wait $PARENT_PID 2>/dev/null if [ "$ZOMBIE_COUNT" -eq 0 ]; then echo -e "${GREEN}✓ PASSED${NC}"