thecodingidiot.com

Who Wants to Be a Game Developer? AcousticStopping Music

Stopping Music

aplay will keep running until it finishes the WAV file or something stops it. A looping WAV never finishes on its own. The parent process must send a signal.

Signals

A signal is a notification the operating system delivers to a process. The process can catch it, ignore it, or let the default action run. The default action for most signals is to terminate the process.

SIGTERM — signal number 15 — is the standard termination signal. It asks the process to exit cleanly. aplay handles it correctly: it stops playback and exits.

kill(pid, signal) sends a signal to a process:

kill(pid, SIGTERM);

After this call, aplay will stop — but it is not yet gone. The process is in a terminated state, waiting for the parent to collect its exit status.

Zombie processes

When a child process terminates, the kernel keeps its entry in the process table — exit status, PID, resource usage — until the parent reads that information. A terminated process waiting in this state is called a zombie.

Zombies do not run, do not use memory, and cannot be signalled. But they occupy a PID slot. If the game creates many zombies without collecting them, it can exhaust the PID namespace.

waitpid(pid, NULL, 0) collects a child's exit status and removes the zombie:

waitpid(pid, NULL, 0);
  • pid — which child to wait for
  • NULL — we do not need the exit status
  • 0 — flags; zero means block until the child exits

After waitpid returns, the child's PID slot is freed.

stop_music

void  stop_music(pid_t pid)
{
    if (pid <= 0)
        return ;
    kill(pid, SIGTERM);
    waitpid(pid, NULL, 0);
}

Replace the stub in music.c with this implementation.

The guard if (pid <= 0) handles two cases: start_music returned -1 (fork failed) and the caller passes that through without checking, or the music was never started and music_pid was never set. In both cases, there is nothing to stop.

Build check

make re
./game questions.txt

The music should now stop when the game ends — win, loss, or walk-away. If you walk away early, you may notice that the music continues for a brief moment after the walk-away message. That is because stop_music is not yet wired into the tier transitions or the exit paths — that is the next page.