CodeBlanks Logo Icon CodeBlanks

kill

Learn to send signals with kill.

The kill function

kill(pid, sig) sends a signal to a specific process. A positive pid targets that process, 0 targets the process group, -1 targets all processes the caller owns.

It returns 0 on success, -1 on error. To send a signal to itself, a process uses kill(getpid(), sig); same as raise(sig). The kill command-line tool uses the same system call.

Signal sending patterns

A parent can send a termination request to a child with kill(child_pid, SIGTERM). Two processes can use SIGUSR1 and SIGUSR2 for custom signaling.

Before sending, make sure the receiver has a handler installed; otherwise the default action (usually termination) applies. Calling kill with signal number 0 checks if the process exists; it sends no signal but tests permissions.

Practice Send to self with kill

Define int caught = 0; and void handler(int sig) with caught = 1;. Register with signal(SIGUSR1, handler);. Send to self with kill(getpid(), SIGUSR1);. Print with printf("caught=%d\n", caught);.

Starter code

main.c
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

int caught = 0;

// Write handler function
// Register with signal
// kill to self and print

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

int caught = 0;

void handler(int sig) {
    caught = 1;
}

int main(void) {
    signal(SIGUSR1, handler);
    kill(getpid(), SIGUSR1);
    printf("caught=%d\n", caught);
    return 0;
}

Expected output

caught=1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does kill(getpid(), SIGUSR1) do?

  • Sends to another process
  • Blocks the signal
  • Sends to the process group
  • Sends to itself Correct answer

Explanation: kill(getpid(), ...) sends a signal to the process itself.

2 Match sending concepts

Term Meaning
kill Sends signal
getpid Own PID
raise Signal to self
SIGTERM Termination request

3 kill call

Question
kill(____(), SIGUSR1);
Answer
kill(getpid(), SIGUSR1);

Explanation: kill(getpid(), SIGUSR1) sends a signal to itself.

All lessons in Advanced