pkill Command in Linux

Topics Covered

Overview

In the world of Linux, every command plays an integral role in system administration or in everyday tasks. The 'pkill' command in Linux is one such powerful tool, often used by system administrators to terminate or signal processes. The beauty of the pkill command in Linux lies in its ability to match processes by their names, instead of process IDs, making it an essential tool for managing processes.

Syntax of pkill Command in Linux

The basic syntax of the pkill command in Linux is as follows:

Where:

  • options: These are optional and modify the behavior of the pkill command.
  • signal: This is also optional. It's the signal to be sent to the processes. The default signal is SIGTERM.
  • pattern: This is the name or part of the name of the processes to be signaled. This is required.

Options in pkill Command in Linux

  1. -l, --list: Lists all known signal names.

    For example -

    Output:

    This command outputs a list of all signals that pkill can send.

  2. -f, --full: Matches the pattern against the entire command line.

    For example -

    This command will terminate all processes whose command line matches 'my_long_running_script'.

  3. -u, --user: Only match processes belonging to certain users.

    For example -

    This command will kill all 'python' processes owned by the user 'john'.

Example Usages

  • Basic usage of pkill command to terminate a process:

    Explanation: This command will terminate all processes named 'python'.

  • Using pkill to send a specific signal:

    Explanation: This command sends the SIGHUP signal to all processes named 'nginx', typically causing them to reload their configuration.

Tips

  • Always double-check the pattern you're using with pkill, as an incorrect pattern could terminate unintended processes.

  • Use pgrep before pkill to list the processes that will be terminated.

Advanced Use Cases of pkill Command in Linux

  • Using pkill to send a signal to processes older than a certain time:

    Explanation: This command will kill the oldest 'python' process owned by the user 'john'.

  • Using pkill to terminate processes running on a specific terminal:

    Explanation: This command will terminate all processes running on terminal pts/5.

  • Combining pkill with other commands using pipe:

    Explanation: This command chain will terminate all processes whose command line matches 'long_running_script'.

Conclusion

  • The pkill command in Linux provides a powerful way to signal processes by name.

  • Pkill supports a variety of options to match processes based on different attributes.

  • Care should be taken while using pkill as it can terminate critical system processes if used incorrectly.