- All You Need To Know About Processes in Linux [Comprehensive Guide]
- Types of Processes
- What is Daemons
- Creation of a Processes in Linux
- How Does Linux Identify Processes?
- The Init Process
- Starting a Process in Linux
- Linux Background Jobs
- States of a Process in Linux
- How to View Active Processes in Linux
- 1. ps Command
- 2. top – System Monitoring Tool
- 3. glances – System Monitoring Tool
- How to Control Processes in Linux
- Sending Signals To Processes
- Changing Linux Process Priority
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Linux-processes
All You Need To Know About Processes in Linux [Comprehensive Guide]
In this article, we will walk through a basic understanding of processes and briefly look at how to manage processes in Linux using certain commands.
A process refers to a program in execution; it’s a running instance of a program. It is made up of the program instruction, data read from files, other programs or input from a system user.
Types of Processes
There are fundamentally two types of processes in Linux:
- Foreground processes (also referred to as interactive processes) – these are initialized and controlled through a terminal session. In other words, there has to be a user connected to the system to start such processes; they haven’t started automatically as part of the system functions/services.
- Background processes (also referred to as non-interactive/automatic processes) – are processes not connected to a terminal; they don’t expect any user input.
What is Daemons
These are special types of background processes that start at system startup and keep running forever as a service; they don’t die. They are started as system tasks (run as services), spontaneously. However, they can be controlled by a user via the init process.
Linux Process State
Creation of a Processes in Linux
A new process is normally created when an existing process makes an exact copy of itself in memory. The child process will have the same environment as its parent, but only the process ID number is different.
There are two conventional ways used for creating a new process in Linux:
- Using The System() Function – this method is relatively simple, however, it’s inefficient and has significantly certain security risks.
- Using fork() and exec() Function – this technique is a little advanced but offers greater flexibility, speed, together with security.
How Does Linux Identify Processes?
Because Linux is a multi-user system, meaning different users can be running various programs on the system, each running instance of a program must be identified uniquely by the kernel.
And a program is identified by its process ID (PID) as well as it’s parent processes ID (PPID), therefore processes can further be categorized into:
- Parent processes – these are processes that create other processes during run-time.
- Child processes – these processes are created by other processes during run-time.
The Init Process
Init process is the mother (parent) of all processes on the system, it’s the first program that is executed when the Linux system boots up; it manages all other processes on the system. It is started by the kernel itself, so in principle it does not have a parent process.
The init process always has process ID of 1. It functions as an adoptive parent for all orphaned processes.
You can use the pidof command to find the ID of a process:
Find Linux Process ID
To find the process ID and parent process ID of the current shell, run:
Find Linux Parent Process ID
Starting a Process in Linux
Once you run a command or program (for example cloudcmd – CloudCommander), it will start a process in the system. You can start a foreground (interactive) process as follows, it will be connected to the terminal and a user can send input it:
Start Linux Interactive Process
Linux Background Jobs
To start a process in the background (non-interactive), use the & symbol, here, the process doesn’t read input from a user until it’s moved to the foreground.
Start Linux Process in Background
You can also send a process to the background by suspending it using [Ctrl + Z] , this will send the SIGSTOP signal to the process, thus stopping its operations; it becomes idle:
To continue running the above-suspended command in the background, use the bg command:
To send a background process to the foreground, use the fg command together with the job ID like so:
Linux Background Process Jobs
States of a Process in Linux
During execution, a process changes from one state to another depending on its environment/circumstances. In Linux, a process has the following possible states:
- Running – here it’s either running (it is the current process in the system) or it’s ready to run (it’s waiting to be assigned to one of the CPUs).
- Waiting – in this state, a process is waiting for an event to occur or for a system resource. Additionally, the kernel also differentiates between two types of waiting processes; interruptible waiting processes – can be interrupted by signals and uninterruptible waiting processes – are waiting directly on hardware conditions and cannot be interrupted by any event/signal.
- Stopped – in this state, a process has been stopped, usually by receiving a signal. For instance, a process that is being debugged.
- Zombie – here, a process is dead, it has been halted but it’s still has an entry in the process table.
How to View Active Processes in Linux
There are several Linux tools for viewing/listing running processes on the system, the two traditional and well known are ps and top commands:
1. ps Command
It displays information about a selection of the active processes on the system as shown below:
List Linux Active Processes
2. top – System Monitoring Tool
List Linux Running Processes
Read this for more top usage examples: 12 TOP Command Examples in Linux
3. glances – System Monitoring Tool
glances is a relatively new system monitoring tool with advanced features:
Glances – Linux Process Monitoring
There are several other useful Linux system monitoring tools you can use to list active processes, open the link below to read more about them:
How to Control Processes in Linux
Linux also has some commands for controlling processes such as kill, pkill, pgrep and killall, below are a few basic examples of how to use them:
Control Linux Processes
To learn how to use these commands in-depth, to kill/terminate active processes in Linux, open the links below:
Note that you can use them to kill unresponsive applications in Linux when your system freezes.
Sending Signals To Processes
The fundamental way of controlling processes in Linux is by sending signals to them. There are multiple signals that you can send to a process, to view all the signals run:
List All Linux Signals
To send a signal to a process, use the kill, pkill or pgrep commands we mentioned earlier on. But programs can only respond to signals if they are programmed to recognize those signals.
And most signals are for internal use by the system, or for programmers when they write code. The following are signals which are useful to a system user:
- SIGHUP 1 – sent to a process when its controlling terminal is closed.
- SIGINT 2 – sent to a process by its controlling terminal when a user interrupts the process by pressing [Ctrl+C] .
- SIGQUIT 3 – sent to a process if the user sends a quit signal [Ctrl+D] .
- SIGKILL 9 – this signal immediately terminates (kills) a process and the process will not perform any clean-up operations.
- SIGTERM 15 – this a program termination signal (kill will send this by default).
- SIGTSTP 20 – sent to a process by its controlling terminal to request it to stop (terminal stop); initiated by the user pressing [Ctrl+Z] .
The following are kill commands examples to kill the Firefox application using its PID once it freezes:
To kill an application using its name, use pkill or killall like so:
Changing Linux Process Priority
On the Linux system, all active processes have a priority and certain nice value. Processes with higher priority will normally get more CPU time than lower priority processes.
However, a system user with root privileges can influence this with the nice and renice commands.
From the output of the top command, the NI shows the process nice value:
List Linux Running Processes
Use the nice command to set a nice value for a process. Keep in mind that normal users can attribute a nice value from zero to 20 to processes they own.
Only the root user can use negative nice values.
To renice the priority of a process, use the renice command as follows:
Check out our some useful articles on how to manage and control Linux processes.
That’s all for now! Do you have any questions or additional ideas, share them with us via the feedback form below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Linux-processes
A RUNNING INSTANCE OF A PROGRAM IS CALLED A PROCESS . If you have two
terminal windows showing on your screen, then you are probably running the same terminal program twice—you have two terminal processes. Each terminal
window is probably running a shell; each running shell is another process.When you invoke a command from a shell, the corresponding program is executed in a new process; the shell process resumes when that process completes.
Advanced programmers often use multiple cooperating processes in a single application to enable the application to do more than one thing at once, to increase application robustness, and to make use of already-existing programs.
Most of the process manipulation functions described in this chapter are similar to those on other UNIX systems. Most are declared in the header file ; check the man page for each function to be sure.
3.1 Looking at Processes
Even as you sit down at your computer, there are processes running. Every executing program uses one or more processes. Let’s start by taking a look at the processes already on your computer.
46 Chapter 3 Processes
3.1.1 Process IDs
Each process in a Linux system is identified by its unique process ID , sometimes referred to as pid . Process IDs are 16-bit numbers that are assigned sequentially by Linux as new processes are created.
Every process also has a parent process (except the special init process, described in Section 3.4.3, “Zombie Processes”).Thus, you can think of the processes on a Linux system as arranged in a tree, with the init process at its root.The parent process ID , or ppid , is simply the process ID of the process’s parent.
When referring to process IDs in a C or C++ program, always use the pid_t typedef, which is defined in . A program can obtain the process ID of the process it’s running in with the getpid() system call, and it can obtain the process ID of its parent process with the getppid() system call. For instance, the program in Listing 3.1 prints its process ID and its parent’s process ID.
Listing 3.1 ( print-pid.c ) Printing the Process ID
printf (“The process ID is %d\n”, (int) getpid ());
printf (“The parent process ID is %d\n”, (int) getppid ()); return 0;
Observe that if you invoke this program several times, a different process ID is reported because each invocation is in a new process. However, if you invoke it every time from the same shell, the parent process ID (that is, the process ID of the shell process) is the same.
3.1.2 Viewing Active Processes
The ps command displays the processes that are running on your system.The GNU/Linux version of ps has lots of options because it tries to be compatible with versions of ps on several other UNIX variants.These options control which processes are listed and what information about each is shown.
By default, invoking ps displays the processes controlled by the terminal or terminal window in which ps is invoked. For example:
3.1 Looking at Processes
This invocation of ps shows two processes.The first, bash , is the shell running on this terminal.The second is the running instance of the ps program itself.The first column, labeled PID , displays the process ID of each.
For a more detailed look at what’s running on your GNU/Linux system, invoke this:
% ps -e -o pid,ppid,command
The -e option instructs ps to display all processes running on the system.The
-o pid,ppid,command option tells ps what information to show about each process— in this case, the process ID, the parent process ID, and the command running in this process.
ps Output Formats
With the -o option to the ps command, you specify the information about processes that you want in the output as a comma-separated list. For example, ps -o pid,user,start_time,command displays the process ID, the name of the user owning the process, the wall clock time at which the process started, and the command running in the process. See the man page for ps for the full list of field codes. You can use the -f (full listing), -l (long listing), or -j (jobs listing) options instead to get three different preset listing formats.
Here are the first few lines and last few lines of output from this command on my system.You may see different output, depending on what’s running on your system.
% ps -e -o pid,ppid,command PID PPID COMMAND
ps -e -o pid,ppid,command
Note that the parent process ID of the ps command, 21727, is the process ID of bash , the shell from which I invoked ps .The parent process ID of bash is in turn 21725, the process ID of the xterm program in which the shell is running.
3.1.3 Killing a Process
You can kill a running process with the kill command. Simply specify on the command line the process ID of the process to be killed.
The kill command works by sending the process a SIGTERM , or termination, signal. 1 This causes the process to terminate, unless the executing program explicitly handles or masks the SIGTERM signal. Signals are described in Section 3.3, “Signals.”
1.You can also use the kill command to send other signals to a process.This is described in Section 3.4, “Process Termination.”
48 Chapter 3 Processes
3.2 Creating Processes
Two common techniques are used for creating a new process.The first is relatively simple but should be used sparingly because it is inefficient and has considerably security risks.The second technique is more complex but provides greater flexibility, speed, and security.
3.2.1 Using system
The system function in the standard C library provides an easy way to execute a command from within a program, much as if the command had been typed into a shell. In fact, system creates a subprocess running the standard Bourne shell ( /bin/sh ) and hands the command to that shell for execution. For example, this program in Listing 3.2 invokes the ls command to display the contents of the root directory, as if you typed ls -l / into a shell.
Listing 3.2 ( system.c ) Using the system Call
return_value = system (“ls -l /”); return return_value;
The system function returns the exit status of the shell command. If the shell itself cannot be run, system returns 127; if another error occurs, system returns –1.
Because the system function uses a shell to invoke your command, it’s subject to the features, limitations, and security flaws of the system’s shell.You can’t rely on the availability of any particular version of the Bourne shell. On many UNIX systems, /bin/sh is a symbolic link to another shell. For instance, on most GNU/Linux systems, /bin/sh points to bash (the Bourne-Again SHell), and different GNU/Linux distributions use different versions of bash . Invoking a program with root privilege with the system function, for instance, can have different results on different GNU/Linux systems.Therefore, it’s preferable to use the fork and exec method for creating processes.
3.2.2 Using fork and exec
The DOS and Windows API contains the spawn family of functions.These functions take as an argument the name of a program to run and create a new process instance of that program. Linux doesn’t contain a single function that does all this in one step. Instead, Linux provides one function, fork , that makes a child process that is an exact
3.2 Creating Processes
copy of its parent process. Linux provides another set of functions, the exec family, that causes a particular process to cease being an instance of one program and to instead become an instance of another program.To spawn a new process, you first use fork to make a copy of the current process.Then you use exec to transform one of these processes into an instance of the program you want to spawn.
When a program calls fork , a duplicate process, called the child process , is created.The parent process continues executing the program from the point that fork was called. The child process, too, executes the same program from the same place.
So how do the two processes differ? First, the child process is a new process and therefore has a new process ID, distinct from its parent’s process ID. One way for a program to distinguish whether it’s in the parent process or the child process is to call getpid . However, the fork function provides different return values to the parent and child processes—one process “goes in” to the fork call, and two processes “come out,” with different return values.The return value in the parent process is the process ID of the child.The return value in the child process is zero. Because no process ever has a process ID of zero, this makes it easy for the program whether it is now running as the parent or the child process.
Listing 3.3 is an example of using fork to duplicate a program’s process. Note that the first block of the if statement is executed only in the parent process, while the else clause is executed in the child process.
Listing 3.3 ( fork.c ) Using fork to Duplicate a Program’s Process
#include #include #include
printf (“the main program process ID is %d\n”, (int) getpid ());
child_pid = fork (); if (child_pid != 0) <
printf (“this is the parent process, with id %d\n”, (int) getpid ()); printf (“the child’s process ID is %d\n”, (int) child_pid);
printf (“this is the child process, with id %d\n”, (int) getpid ());
50 Chapter 3 Processes
Using the exec Family
The exec functions replace the program running in a process with another program. When a program calls an exec function, that process immediately ceases executing that program and begins executing a new program from the beginning, assuming that the exec call doesn’t encounter an error.
Within the exec family, there are functions that vary slightly in their capabilities and how they are called.
n Functions that contain the letter p in their names ( execvp and execlp ) accept a program name and search for a program by that name in the current execution path; functions that don’t contain the p must be given the full path of the program to be executed.
n Functions that contain the letter v in their names ( execv , execvp , and execve ) accept the argument list for the new program as a NULL-terminated array of pointers to strings. Functions that contain the letter l ( execl , execlp , and execle ) accept the argument list using the C language’s varargs mechanism.
n Functions that contain the letter e in their names ( execve and execle ) accept an
additional argument, an array of environment variables.The argument should be a NULL-terminated array of pointers to character strings. Each character string should be of the form “ VARIABLE=value ”.
Because exec replaces the calling program with another one, it never returns unless an error occurs.
The argument list passed to the program is analogous to the command-line arguments that you specify to a program when you run it from the shell.They are available through the argc and argv parameters to main . Remember, when a program is invoked from the shell, the shell sets the first element of the argument list argv[0] ) to the name of the program, the second element of the argument list ( argv[1] ) to the first command-line argument, and so on.When you use an exec function in your programs, you, too, should pass the name of the function as the first element of the argument list.
Using fork and exec Together
A common pattern to run a subprogram within a program is first to fork the process and then exec the subprogram.This allows the calling program to continue execution in the parent process while the calling program is replaced by the subprogram in the child process.
The program in Listing 3.4, like Listing 3.2, lists the contents of the root directory using the ls command. Unlike the previous example, though, it invokes the ls command directly, passing it the command-line arguments -l and / rather than invoking it through a shell.
3.2 Creating Processes
Listing 3.4 ( fork-exec.c ) Using fork and exec Together
#include #include #include #include
/* Spawn a child process running a new program. PROGRAM is the name of the program to run; the path will be searched for this program. ARG_LIST is a NULL-terminated list of character strings to be passed as the program’s argument list. Returns the process ID of the spawned process. */
int spawn (char* program, char** arg_list)
/* Duplicate this process. */ child_pid = fork ();
if (child_pid != 0)
/* This is the parent process. */ return child_pid;
/* Now execute PROGRAM, searching for it in the path. */ execvp (program, arg_list);
/* The execvp function returns only if an error occurs. */ fprintf (stderr, “an error occurred in execvp\n”);
/* The argument list to pass to the “ls” command. */ char* arg_list[] = <
/* argv[0], the name of the program. */
/* The argument list must end with a NULL. */
/* Spawn a child process running the “ls” command. Ignore the returned child process ID. */
spawn (“ls”, arg_list);
printf (“done with main program\n”);
52 Chapter 3 Processes
3.2.3 Process Scheduling
Linux schedules the parent and child processes independently; there’s no guarantee of which one will run first, or how long it will run before Linux interrupts it and lets the other process (or some other process on the system) run. In particular, none, part, or all of the ls command may run in the child process before the parent completes. 2 Linux promises that each process will run eventually—no process will be completely starved of execution resources.
You may specify that a process is less important—and should be given a lower priority
—by assigning it a higher niceness value. By default, every process has a niceness of zero. A higher niceness value means that the process is given a lesser execution priority; conversely, a process with a lower (that is, negative) niceness gets more execution time.
To run a program with a nonzero niceness, use the nice command, specifying the niceness value with the -n option. For example, this is how you might invoke the command “ sort input.txt > output.txt ”, a long sorting operation, with a reduced priority so that it doesn’t slow down the system too much:
% nice -n 10 sort input.txt > output.txt
You can use the renice command to change the niceness of a running process from the command line.
To change the niceness of a running process programmatically, use the nice function. Its argument is an increment value, which is added to the niceness value of the process that calls it. Remember that a positive value raises the niceness value and thus reduces the process’s execution priority.
Note that only a process with root privilege can run a process with a negative niceness value or reduce the niceness value of a running process.This means that you may specify negative values to the nice and renice commands only when logged in as root, and only a process running as root can pass a negative value to the nice function. This prevents ordinary users from grabbing execution priority away from others using the system.
Signals are mechanisms for communicating with and manipulating processes in Linux. The topic of signals is a large one; here we discuss some of the most important signals and techniques that are used for controlling processes.
A signal is a special message sent to a process. Signals are asynchronous; when a process receives a signal, it processes the signal immediately, without finishing the current function or even the current line of code.There are several dozen different signals, each with a different meaning. Each signal type is specified by its signal number, but in programs, you usually refer to a signal by its name. In Linux, these are defined in /usr/include/bits/signum.h . (You shouldn’t include this header file directly in your programs; instead, use .)
2. A method for serializing the two processes is presented in Section 3.4.1, “Waiting for Process Termination.”
When a process receives a signal, it may do one of several things, depending on the signal’s disposition . For each signal, there is a default disposition , which determines what happens to the process if the program does not specify some other behavior. For most signal types, a program may specify some other behavior—either to ignore the signal or to call a special signal-handler function to respond to the signal. If a signal handler is used, the currently executing program is paused, the signal handler is executed, and, when the signal handler returns, the program resumes.
The Linux system sends signals to processes in response to specific conditions. For instance, SIGBUS (bus error), SIGSEGV (segmentation violation), and SIGFPE (floating point exception) may be sent to a process that attempts to perform an illegal operation.The default disposition for these signals it to terminate the process and produce a core file.
A process may also send a signal to another process. One common use of this mechanism is to end another process by sending it a SIGTERM or SIGKILL signal. 3 Another common use is to send a command to a running program.Two “userdefined” signals are reserved for this purpose: SIGUSR1 and SIGUSR2 .The SIGHUP signal is sometimes used for this purpose as well, commonly to wake up an idling program or cause a program to reread its configuration files.
The sigaction function can be used to set a signal disposition.The first parameter is the signal number.The next two parameters are pointers to sigaction structures; the first of these contains the desired disposition for that signal number, while the second receives the previous disposition.The most important field in the first or second sigaction structure is sa_handler . It can take one of three values:
n SIG_DFL , which specifies the default disposition for the signal.
n SIG_IGN , which specifies that the signal should be ignored.
n A pointer to a signal-handler function.The function should take one parameter,
the signal number, and return void .
Because signals are asynchronous, the main program may be in a very fragile state when a signal is processed and thus while a signal handler function executes. Therefore, you should avoid performing any I/O operations or calling most library and system functions from signal handlers.
A signal handler should perform the minimum work necessary to respond to the signal, and then return control to the main program (or terminate the program). In most cases, this consists simply of recording the fact that a signal occurred.The main program then checks periodically whether a signal has occurred and reacts accordingly.
It is possible for a signal handler to be interrupted by the delivery of another signal. While this may sound like a rare occurrence, if it does occur, it will be very difficult to diagnose and debug the problem. (This is an example of a race condition, discussed in Chapter 4, “Threads,” Section 4.4, “Synchronization and Critical Sections.”) Therefore, you should be very careful about what your program does in a signal handler.
3.What’s the difference? The SIGTERM signal asks a process to terminate; the process may ignore the request by masking or ignoring the signal.The SIGKILL signal always kills the process immediately because the process may not mask or ignore SIGKILL .
54 Chapter 3 Processes
Even assigning a value to a global variable can be dangerous because the assignment may actually be carried out in two or more machine instructions, and a second signal may occur between them, leaving the variable in a corrupted state. If you use a global variable to flag a signal from a signal-handler function, it should be of the special type sig_atomic_t . Linux guarantees that assignments to variables of this type are performed in a single instruction and therefore cannot be interrupted midway. In Linux, sig_atomic_t is an ordinary int ; in fact, assignments to integer types the size of int or smaller, or to pointers, are atomic. If you want to write a program that’s portable to any standard UNIX system, though, use sig_atomic_t for these global variables.
This program skeleton in Listing 3.5, for instance, uses a signal-handler function to count the number of times that the program receives SIGUSR1 , one of the signals reserved for application use.
Listing 3.5 ( sigusr1.c ) Using a Signal Handler
#include #include #include #include #include
sig_atomic_t sigusr1_count = 0;
void handler (int signal_number)
struct sigaction sa;
/* Do some lengthy stuff here. */ /* . */
printf (“SIGUSR1 was raised %d times\n”, sigusr1_count); return 0;
Источник