Added semaphore_basic exercice and fixed the tester.

This commit is contained in:
Rui Ribeiro 2025-10-14 20:37:03 +01:00
parent be7c0d17bb
commit a775f2b41a
2 changed files with 96 additions and 1 deletions

95
rendu/semaphore_basics.c Normal file
View File

@ -0,0 +1,95 @@
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* 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);
}

View File

@ -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}"