Skip to content

2.2 Process

1. Basics

Fundamentals of process and program.

1.1 What is a Program?

A program is a set of instructions written in a programming language that tells the computer what to do. A program is a passive entity stored on a storage device (like a hard drive, SSD, etc.), such as a text file or an executable file, that contains code and resources needed to perform specific tasks when executed. It is not running yet; it is just a file on disk.

  • Example: A compiled binary file (./hello) or a script (script.sh).

1.2 What is a Process?

A process is an instance of a program that is currently being executed by the computer. When you run a program, the operating system creates a process that includes the program code, its current activity, and its allocated resources (such as memory, CPU time, and file handles). The process is dynamic, meaning it’s actively running.

Key attributes of a process include:

  1. Program Code (text section): The actual code that is executed.
  2. Program Counter: A register that holds the address of the next instruction to execute.
  3. Process Stack: Contains the execution history of function calls.
  4. Heap: Dynamically allocated memory.
  5. File Descriptors: Handles to open files or other resources (e.g., sockets).
  6. Process State: The current status of the process (running, waiting, stopped, etc.).

When a program is executed multiple times, each execution is a different process.

1.3 Difference

  • A program is static; it’s just a file on disk.
  • A process is dynamic; it’s a program in execution.

2. Processes in Linux

In Linux, processes are fundamental to how the system works. Here are key concepts and commands to work with processes:

2.1 Viewing Processes

  • ps (Process Status): The ps command is used to view information about active processes.
    • Basic usage: ps

    • Shows processes running in the current shell.

    • Common options:

      • ps -e or ps -A: Show all processes.
      • ps -ef: Show all processes with full details.
      • ps aux: Show all processes with detailed information (including processes from all users).

      Example:

      Terminal window
      ps aux

2.2 Top Command

  • top: The top command provides a real-time, dynamic view of the system’s processes. It shows details like CPU usage, memory usage, process IDs, and more. It constantly updates its display, making it useful for monitoring system performance.

    • To view the top processes: top
    • Press q to quit the top view.

    Key metrics shown by top:

    • PID: Process ID.
    • USER: The owner of the process.
    • %CPU: Percentage of CPU usage by the process.
    • %MEM: Percentage of memory usage by the process.
    • TIME+: Total CPU time the process has used.
    • COMMAND: The command or program that started the process.

2.3 htop** (Improved Version of `top

  • htop: A more user-friendly version of top with a graphical interface (works in the terminal). It allows users to interactively sort processes, kill them, and display additional stats.

    • To install htop (if not already installed):

      Terminal window
      sudo apt install htop # For Debian/Ubuntu-based systems
      sudo yum install htop # For CentOS/RHEL-based systems
    • To launch htop: htop

    Key features of htop:

    • Easier-to-read interface with color-coded information.
    • Interactive process management.
    • Allows you to search and filter processes.
    • Can kill processes directly from the interface.

2.4 Managing Processes

  • kill: The kill command is used to send a signal to a process. The most common signal is SIGTERM (which asks the process to terminate), but you can also send other signals like SIGKILL (forceful termination).

    Example:

    • To kill a process by PID:

      Terminal window
      kill <PID>
    • To forcefully kill a process:

      Terminal window
      kill -9 <PID>

    Important Signals:

    • SIGTERM (15): Graceful termination.
    • SIGKILL (9): Forceful termination.
    • SIGSTOP (19): Stop a process (it can be resumed later).
  • bg and fg: Commands used to manage background and foreground jobs.

    • bg: Moves a job to the background.
    • fg: Brings a background job to the foreground.

    Example:

    • To send a running process to the background:
      Terminal window
      ctrl+z # Suspend the process
      bg # Send the process to the background
  • nice and renice: Used to set or adjust the priority of processes.

    • nice: Start a process with a specific priority.
    • renice: Change the priority of an already running process.

    Example:

    • To start a process with lower priority:
      Terminal window
      nice -n 10 command_name

2.5 Process Hierarchy

  • pstree: Displays processes in a tree-like format, showing the parent-child relationship between processes.

    Example:

    Terminal window
    pstree
  • Parent Process and Child Process:

    • Every process in Linux has a parent process (except the root process, PID 1, usually init or systemd).
    • Processes can spawn child processes. The parent process can control or manage the execution of its children.
  • pgrep: Searches for processes based on name or other criteria.

    Terminal window
    pgrep firefox # Find the PID of Firefox processes
  • pidof: Finds the PID of a running program.

    Terminal window
    pidof firefox
  • lsof: Lists open files and the processes using them.

    Terminal window
    lsof -i :8080 # Show processes using port 8080
  • strace: Traces system calls and signals. Useful for debugging or analyzing what a process is doing at the system level.

    Terminal window
    strace -p <PID>

2.7 Zombie and Orphan Processes

  • Zombie Process: A process that has finished execution but still has an entry in the process table because its parent hasn’t read its exit status. It’s essentially “dead” but not fully cleaned up.

    • These can be cleaned up by ensuring the parent process calls wait() to collect the exit status.
  • Orphan Process: A process whose parent has finished execution. These processes are adopted by init (or systemd on modern systems).

2.8 Daemon Processes

  • Daemon: A background process that runs independently of user interaction, often performing system maintenance tasks. Examples include web servers (httpd), databases, or system services.

3. Background vs Foreground Process

In Linux (and Unix-like systems), background and foreground processes refer to how a process is managed in relation to the terminal or shell session from which it is started. These terms describe whether a process runs in the foreground (actively interacting with the user) or the background (running independently of the user’s direct interaction).

3.1 Foreground Process

A foreground process is a process that runs directly in the terminal or shell where it was started. This means that the process has control of the terminal and the user interacts with it directly. It takes the input and sends output to the terminal.

  • User Interaction: The user can interact with the process in real-time, providing inputs and seeing its output directly.
  • Blocking: While a foreground process is running, the terminal is blocked (i.e., you cannot run any other commands in that terminal until the process finishes).
  • Example: Running a program like vim, nano, or a long-running command like tar to archive files.

Example of a Foreground Process:

Terminal window
$ tar -czf archive.tar.gz /path/to/directory # This command runs in the foreground

In this case, the terminal is blocked until the tar command completes.

3.2 Background Process

A background process is a process that runs independently of the terminal or shell. It doesn’t block the terminal or shell, and the user can continue using the terminal to issue new commands while the background process runs.

  • User Interaction: The process does not interact with the terminal directly. It runs in the background and outputs results to a file or standard output.
  • Non-blocking: Since it’s running in the background, it doesn’t block the terminal, and you can continue using it for other tasks.
  • Sign: In Linux, background processes are usually represented by an & symbol when launched from the shell.

Example of a Background Process:

Terminal window
$ tar -czf archive.tar.gz /path/to/directory & # The tar command runs in the background

In this case, the tar command is sent to the background, and the shell prompt is immediately available for the user to issue new commands.

You can also run a process in the background after it has already started in the foreground by suspending it and then sending it to the background.

  1. Start a process (for example, a long-running command):

    Terminal window
    $ sleep 100 # A process that simply sleeps for 100 seconds
  2. Suspend it with Ctrl + Z. This will stop (pause) the process and put it in the background.

    Terminal window
    [1]+ 12345 suspended sleep 100 # The process is suspended (PID 12345)
  3. Move it to the background with the bg command:

    Terminal window
    $ bg 12345 # Send the process with PID 12345 to the background
  4. To bring it back to the foreground, use the fg command:

    Terminal window
    $ fg 12345 # Bring the process back to the foreground

3.3 Key Differences

FeatureForeground ProcessBackground Process
Control of TerminalTakes control of the terminal and interacts with itRuns independently of the terminal
User InteractionUser can interact with the process directlyProcess runs without direct interaction
BlockingBlocks the terminal until the process finishesDoes not block the terminal; allows other commands
Execution SymbolNo special symbolAppended with & symbol to indicate background execution
Job ControlNo job control requiredCan be controlled using bg, fg, jobs, kill

3.4 Managing Background Processes

  1. Listing Background Processes: You can see a list of background jobs with the jobs command:

    Terminal window
    $ jobs

    This will show background jobs in the current shell session. For example:

    Terminal window
    [1] 12345 sleep 100 # Process 12345 is running in the background
  2. Bring Background Process to Foreground: You can bring a background process to the foreground using the fg command:

    Terminal window
    $ fg %1 # Bring job 1 to the foreground
  3. Sending a Process to the Background: If a process is running in the foreground, you can suspend it with Ctrl + Z and send it to the background using the bg command:

    Terminal window
    $ bg %1 # Send job 1 to the background
  4. Killing Background Processes: You can kill a background process using the kill command with its process ID (PID) or job number:

    Terminal window
    $ kill %1 # Kill job 1

    Alternatively, you can use the PID of the process:

    Terminal window
    $ kill 12345 # Kill process with PID 12345

Practical Examples

  1. Running a Program in the Foreground:

    Terminal window
    $ ./long_running_task # This will run the task in the foreground, blocking the terminal
  2. Running a Program in the Background:

    Terminal window
    $ ./long_running_task & # This runs the task in the background
  3. Starting a Program in the Background After It’s Running in the Foreground:

    Terminal window
    $ long_running_task # Start a long task in the foreground
    # Press Ctrl+Z to suspend the task
    $ bg # Send the suspended task to the background
  4. Viewing Background Jobs:

    Terminal window
    $ jobs # List jobs running in the background