Course contentsShow
← C
Lesson 1086 of 1,21915. Systems ProgrammingFree lesson

Sending signals with kill()

Sending signals with kill()

What you'll learn: How to use the kill() function to send specific software interrupts from one process to another.

The Software "Poke"

Imagine you are sitting in a library. If you want someone across the room to stop talking, you might catch their eye and mimic a "zipper" motion over your mouth. You haven't physically moved them, but you sent a specific signal that tells them to change their behavior.

In systems programming, the kill() function is that "poke." Despite its aggressive name, kill() doesn't always terminate a program. It is simply the primary tool used to send signals—small notifications—between processes.

Using the kill() Function

To send a signal, you need two pieces of information: the PID (Process ID) of the target and the Signal Name (the type of message).

The syntax looks like this: int result = kill(pid_t pid, int sig);

  • pid: The unique ID of the process you want to talk to.
  • sig: The signal constant (like SIGTERM to ask it to stop, or SIGUSR1 for a custom message).

A Concrete Example

In this snippet, a parent process creates a child, lets it work for a moment, and then sends a "terminate" signal to tell the child it's time to pack up.

#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

int main() {
    pid_t child_pid = fork();

    if (child_pid == 0) {
        // Child process: Loop forever
        while(1) {
            printf("Child: I'm working...\n");
            sleep(1);
        }
    } else {
        // Parent process: Wait 3 seconds, then send a signal
        sleep(3);
        printf("Parent: Sending SIGTERM to child %d\n", child_pid);
        
        // kill() returns 0 on success
        if (kill(child_pid, SIGTERM) == 0) {
            printf("Parent: Signal sent successfully.\n");
        }
    }

    return 0;
}

Permissions and Safety

You can't just send signals to any process on your computer. The operating system acts as a bouncer; you generally can only send signals to processes that you own. If you try to kill() a process belonging to another user or the System, the function will return -1 and set errno to indicate that permission was denied.

Key takeaway

The kill() function is the standard way to send signals (interrupts) to a specific process using its PID.