linux-sysprog · intermediate · ~15 min

Parent process signals a child

Use fork + kill + waitpid to coordinate signal delivery.

Challenge

Coordinate a parent and a child process through a signal: the parent forks a worker, then sends it SIGUSR1 to make it exit, and collects its exit status.

Task

Implement int signal_child_to_exit(int seconds) that forks a child, signals it, and returns the child's exit code.

Input

  • seconds: how long the parent waits before signalling the child. Use usleep for sub-second delays (e.g. when seconds == 0, give the child a brief moment to install its handler first).

Output

The function should:

  1. fork() a child.
  2. In the child: install a SIGUSR1 handler that calls _exit(7), then pause().
  3. In the parent: wait seconds, then kill(child, SIGUSR1).
  4. In the parent: waitpid for the child and return its exit code (the value passed to _exit, i.e. 7).

Returns -1 on any fork/wait failure.

Example

signal_child_to_exit(0)   ->   7   (child exits via its SIGUSR1 handler)

Edge cases

  • A fork or waitpid failure returns -1.
  • Give the child time to install its handler before signalling.

Why this matters

The classic IPC primitive: parent forks a worker, signals it to stop when work is done.

Input format

seconds: how long the parent waits before sending SIGUSR1 (use usleep for sub-second).

Output format

The child's exit code (7, from its _exit(7) handler), or -1 on fork/wait failure.

Constraints

Child installs a SIGUSR1 handler that _exit(7)s, then pauses; parent kills then waitpids it.

Starter code

#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
int signal_child_to_exit(int seconds) {
    /* TODO */
    return -1;
}

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.