BCE-O535 Linux and Shell Programming

0 of 30 lessons complete (0%)

Module 5 Processes

Process Management

Creating Processes

  • To create a new process, we often use the fork() system call in C or similar functions in other programming languages. This function creates a new child process that is an identical copy of the parent process.

Example in C:

#include <stdio.h> #include <unistd.h> 
int main() {      pid_t child_pid; child_pid = fork(); 
     // Create a new process 
     if (child_pid == 0) 
     { // This code is executed by the child process 
          printf("Child process: PID=%d\n", getpid()); 
     } 
     else if (child_pid > 0) 
     { // This code is executed by the parent process 
          printf("Parent process: PID=%d, Child PID=%d\n", getpid(), child_pid); 
     } 
     else 
     { // fork() failed 
          fprintf(stderr, "Fork failed.\n"); 
          return 1; 
     } 
     return 0; 
}

Terminating Processes

  • Processes can terminate naturally when they reach the end of their code. However, they can also be terminated manually using the kill command or by sending a specific signal.

Example:

# Terminate a process by PID kill <PID> 
# Send SIGTERM (termination) signal to a process kill -15 <PID> 
# Send SIGKILL (forceful termination) signal to a process kill -9 <PID>

Monitoring Processes

  • Use the top command to monitor active processes and their resource usage.
top

Listing Processes (ps command)

  • The ps command provides information about running processes.
ps -ef

Process Priority and Scheduling

  • You can use the nice and renice commands to adjust process priority.
# Launch a process with a specific priority (niceness) nice -n <priority> <command> 
# Change the priority of an existing process renice <priority> -p <PID>

Process Resource Limits

  • You can set resource limits for a process using the ulimit command.
ulimit -n 100 # Set the maximum number of open file descriptors to 100

Engaging Example:

Let’s create a practical scenario:

Suppose you’re running a server program that you want to execute at a higher priority. You’ll launch it with nice and then monitor it using top. If needed, you can adjust its priority using renice.

Example:

# Launch a server with higher priority nice -n -10 ./my_server 
# Monitor processes including your server top 
# If needed, adjust the priority of your server renice -n -5 -p <server_PID>

This example provides hands-on experience in creating, monitoring, and managing processes with priority adjustments. It helps learners understand how to control process behavior and resource allocation.