Most students encounter the Dining Philosophers problem during the common core project. 42 Exam 06 simplifies this: you do not implement the full project. Instead, you typically have to code a smaller version, often referred to as the "One Philosopher" or "Basic Simulation."
The prompt usually reads something like:
Write a program that takes a
number_of_philosophersand atime_to_dieas arguments. Each philosopher is a process. They must eat, sleep, and think. If a philosopher doesnโt start eating beforetime_to_diemilliseconds after their last meal, they die and the simulation stops.
The 42 exam environment provides no GDB (usually). Your only debug tool is write to stderr.
A minimal viable structure:
typedef struct s_minishell char **env; int last_exit; t_minishell;int main(void) t_minishell shell; char *line;
shell.env = init_env(environ); shell.last_exit = 0; while (1) line = readline("minishell$ "); if (!line) // ctrl-D break; if (*line) add_history(line); parse_and_execute(line, &shell); free(line); return (0);
Parsing must handle:
You cannot use pthread_join because you have no threads. You must use waitpid(-1, &status, WNOHANG) in a loop to check which child (philosopher) has died without blocking the monitor.
Hereโs a reconstructed problem from a 2023 42 Exam 06 session:
Subject: Write a program
signal_pingthat takes no arguments. It creates a pipe, then forks twice (Child A and Child B). Child A sendsSIGUSR1to Child B every second. Child B counts how many signals it receives and prints the count every 5 seconds. The parent must terminate both children cleanly when it receivesSIGTERM.
The hidden challenges:
Why cadets fail: They try to use a global variable across processes (impossible without shared memory). They forget that fork copies memory, not shares it.
The correct approach: Use the pipe as a control channel. Parent writes "EXIT" to the pipe, children read from it.
Do not fear sem_open. Memorize this incantation:
sem_t *forks;
forks = sem_open("/forks", O_CREAT, 0644, number_of_philosophers);
// ... later
sem_wait(forks);
// eat
sem_post(forks);
// finally
sem_close(forks);
sem_unlink("/forks");
Warning: The Moulinette resets /dev/shm/. Use unique names like /sem_philo_<pid> to avoid conflicts. 42 Exam 06
Letโs be honest. Most 42 students fail Exam 06 at least once. The reasons are predictable: