Stopping the linux process. Killing processes in Linux - ps, kill and killall commands. Terminate a process in Linux - kill and killall commands

💖 Do you like it? Share the link with your friends

The -9 (or KILL) argument to the kill command should only be used on POSIX-compliant systems when absolutely necessary. Why? The KILL signal cannot be processed by the process. This means that after killing a process with kill -9 , the child processes will remain in memory and become "orphaned" file system will be clogged with temporary files, shared memory segments will be active, sockets will be hung, and the atexit(3) function will not be executed at all. As a result, there is a risk of encountering unexpected and difficult-to-debug problems.

Instead, use the default TERM signal, and KILL only if less problematic signals prove ineffective:

$kill 6738
$ kill -INT 6738
$ kill -HUP 6738
$ kill -KILL 6738

If even the KILL signal fails to kill the process, the process is likely stuck on I/O or in some other unkillable state. You may need to reboot or forcefully unmount the glitched network drive.

Using the default kill -KILL is acceptable when dealing with a problematic application, for example, older versions of Netscape often terminated only with the KILL signal. However, this is a rare exception to the rule: use KILL for these known applications and only for them.

Problems encountered when terminating processes

Sending different signals sequentially can cause the following problems: First, the process may take seconds, or even tens of seconds, to terminate gracefully. One product I used took over 30 seconds to terminate correctly after receiving the TERM signal. Fortunately, this feature was discovered during testing, so a suitable script was written for this case. Secondly, sometimes there are situations where an old process has terminated while a new process has taken over its ID in the interval between the TERM and KILL signals. Systems with high process turnover and systems where the kernel assigns PIDs randomly, such as OpenBSD, are especially at risk of this. Checking the process name or its PPID doesn't always help, since the new process could be a fork of the same parent and have the same name, so particularly paranoid scripts might also check the process's creation time or other metadata before sending the signal. These situations may occur rarely, but they are worth taking into account if you have to deal with a critical process.

Process termination signals

Process termination signals can be identified by name or sequence number: kill -1 and kill -HUP are equivalent. However, using the signal name is safer because specifying a -1 argument can easily mistype it, sending the signal to another process or even a group of processes. Also, always try to use a name in your scripts, as this will help you better understand what type of signal is being sent to whoever will be reading your code.

The HUP signal freezes the shell, so it good way clear the shell hanging waiting for input, or close the SSH session.

For more information about process termination signals, see

Signals are software interrupts. They are used for communication between processes in UNIX and UNIX-like operating systems such as Linux, Mac OS.

Signals have been in use since Bell Labs UNIX in 1970 and are now officially defined by the POSIX standard. When a signal is received by a process, the operating system interrupts the process's normal flow of execution and provides notification.

Doesn't matter which one operating system you use, you will undoubtedly experience that your applications are blocked and refuse to work properly. In Unix, Linux, there is a "kill" command that you can use to kill the process immediately, but not only that, but I will talk about that a little later. In this article “Kill Command in Unix/Linux” I will explain and show you how to ready-made examples various commands kill utilities.

Kill Commands and Signals

When you issue the kill command, you are actually sending a signal to the system and instructing it to terminate the broken application. There are a total of 60 signals that can be used, but all you really need to know are SIGTERM (15) and SIGKILL (9).

You can view all signals using the command:

# kill -l

On my MacOS:

I will try to talk about all the signals, but first we will talk only about the most important and frequently used ones.

Basic signals

The following signals are part POSIX standard. Each signal is a macro defined in System header file. They are usually abbreviated without their SIG prefix; for example SIGHUP is often referred to simply as HUP.

SIGTERM– This signal requests to stop a process that is running. This signal can be ignored. The process is given time to shut down well. When a program shuts down well, it means it has been given time to salvage its progress and free up resources. In other words, it did not "force" the process to terminate.

SIGKILL– The SIGKILL signal causes the process to stop doing its work immediately. The program cannot ignore this signal. Unsaved progress will be lost.

Syntax for "kill".

The command syntax is:

# kill PID(s)

# kill [-s] [-l] %pid

The default signal (if not specified) is SIGTERM. When this signal does not help and does not work, you can use the following options for "kill" to forcefully terminate the process:

# kill SIGKILL PID

# kill -9 PID

where “-9” is the flag that refers to the SIGKILL signal.

If you don’t know what PID to use for the application you want to get rid of, then run the command:

$ps -aux

And if you know a specific application (for example, apache), then you can weed out what is unnecessary and display all processes for this service:

$ ps -aux | grep apache

And this will display all the running applications along with its PID(s).

For example, to kill an application, I run the following command:

# kill -9 3629

It's also worth noting that you can have multiple processes running at the same time so they can be "killed":

# kill -9 PID1 PID2 PID 3

Reload configuration files or restart the utilities:

# kill -1 number_of_PID

Particularly useful signals include HUP, INT, kill, STOP, CONT, and 0.

The options are:

-s signal_name
A symbolic signal name that specifies the signal to send a non-default signal.

-l
If the operand is not specified, then show the signal names; Otherwise, write the name of the signal corresponding to exit_status.

-signal_name
Symbolic signal name that specifies the signal to send to TERM by default.

-signal_number
A non-negative decimal integer that specifies the default signal to send to TERM.

The following PIDs have special meaning:
-1 If the superuser, then broadcasts the signal to all processes; otherwise it broadcasts to all processesbelong-
ing for the user.

Some of the most commonly used signals are:

  • 1 HUP (hang up) - hang up.
  • 2 INT (interrupt) - interruption.
  • 3 QUIT (quit) - exit.
  • 6 ABRT (abort) - interruptions.
  • 9 KILL (non-catchable, non-ignorable kill)
  • 14 ALRM (alarm clock) - alarm clock.
  • 15 TERM (software termination signal) — Software to stop the signal.

PKill

The "pkill" command allows you to use advanced patterns of regular expressions and other matching criteria. Instead of using the PID, you can now kill the application by entering the process name. For example, to kill the Firefox browser, simply run the command:

#pkill Firefox

Because it matches the pattern regular expression, you can also enter part of the process name, like this:

#pkillfire

To avoid "killing" the wrong processes, you can do "pgrep -l [process_name]" to list eligible processes.

The pkill command has many more options, for example if you specify the "-u" option it will allow you to specify a username or ID. In this example, we send the TERM signal to all processes owned by user 'nobody':

# pkill -u nobody

Killall

Killall uses the process name instead of the PID, and it "kills" all instances of the process with the same name. For example, if you are using multiple instances Firefox browser, you can kill them all with the command:

#killall firefox

In Gnome, you can restart Nautilus with the command:

#killallnautilus

xkill

Xkill is graphically"kill" the application. When you enter "XKill" in the terminal, the mouse cursor will immediately become a "cross". All you have to do is press "cross" on the offending app and it will kill the app instantly. If you're interested, you can add a keyboard shortcut to enable the XKill feature.

Other signals that are used

SIGABRT

This signal sends a signal to the process to abort the operation. ABRT is typically directed at the process itself when it calls the C programming language's abort() function to signal an abnormal termination, but it can be directed from any process just like any other signal.

SIGALRM, SIGVTALRM and SIGPROF

ALRM, VTALRM and/or PROF signal is sent to a process when a time limit specified by a call to an alarm function (such as setitimer) has expired.

ALRM

Sent when the present time or clock is passing.

VTALRM

Sent when the CPU time used by a process has expired.

PROF

Sent when CPU time used by a process and the system on behalf of the process expires.

SIGBUS

A BUS signal is sent to a process when it results in a bus error. Conditions that result in this signal, such as memory access misalignment or a missing physical address.

SIGCHLD

The CHLD signal is sent to a process when a child process terminates, is interrupted, or resumes after being interrupted. One common use of a signal is to signal the OS to clean up resources that are being used by a child process after it ends, without an explicit system call.

SIGCONT

The CONT signal instructs the operating system to restart a process that was previously suspended by a STOP or TSTP signal. One of the important features of this signal is to control operation in the Unix shell.

SIGFPE

The FPE signal is sent to a process when it performs erroneous arithmetic operations, such as dividing by zero.

SIGHUP

The HUP signal is sent to a process when its control terminal is closed. It was originally designed to notify a process after successive line drops (HUP responsible for hangs). IN modern systems, this signal usually means that pseudo or virtual terminal control has been closed.

SIGILL

ILL signal sent to a process when it attempts to execute malicious, unknown, or privileged commands (instructions).

SIGINT

The INT signal is sent to a process from the control terminal when the user wishes to terminate the process. This is typically initiated by pressing Control-C, but on some systems, "delete" or "break".

SIGKILL

The KILL signal is sent to a process to stop running immediately. Unlike SIGTERM and SIGINT, this signal cannot be captured or ignored, and the receiving process cannot perform any cleanup after receiving this signal.

SIGPIPE

The PIPE signal is sent to a process when it attempts to write to a pipe without a process connected to the other end.

SIGQUIT

The QUIT signal is sent to a process from its controlling terminal when the user requests the process to perform a dump.

SIGSEGV

The SEGV signal is sent to a process when it makes an invalid virtual memory reference or segmentation fault, that is, when it performs a segmentation violation.

SIGSTOP

The STOP signal tells the OS to stop the process so it can resume later.

SIGTERM

The TERM signal is sent to a process to request that it terminate. Unlike the “kill” signal, it can be interpreted or ignored during the process. This allows the process to perform "nice" execution to stop releasing resources and save state if necessary. It should be noted that SIGINT is almost identical to SIGTERM.

SIGTSTP

The TSTP signal is sent to its control terminal process and tells it to temporarily suspend. This is usually initiated by the user pressing Control-Z. Unlike SIGSTOP, this process can register a signal handler or to ignore the signal.

SIGTTIN and SIGTTOU

The TTIN and TTOU signals are sent to a process when it attempts to read or write, respectively, from a (tty) terminal in the background. As a rule, this signal can only be obtained using processes under control working panel; daemons do not have control terminals and should never receive this signal.

SIGUSR1 and SIGUSR2

Signals USR1 and USR2 are sent to the process and indicate user-defined conditions.

SIGPOLL

The POLL signal is sent to a process when an asynchronous I/O event occurs.

SIGSYS

The SYS signal is sent to a process when it passes a bad argument to a system call.

SIGTRAP

A TRAP signal is sent to a process when a condition occurs that the debugger has asked to be informed of—for example, when a particular function is executed or when a particular value of a variable changes.

SIGURG

The URG signal is sent to a process when the socket has urgent or out-of-range data available for reading.

SIGXCPU

The XCPU signal is sent to a process when it uses the CPU for a time exceeding a certain set point set by the user. The arrival of the XCPU signal ensures that the process quickly saves all intermediate results and exits well before it is terminated by the operating system using the SIGKILL signal.

SIGXFSZ

The XFSZ signal is sent in the process when a file grows larger (exceeds a specified value) than the maximum allowed value.

SIGRTMIN to SIGRTMAX

The RTMIN - RTMAX signals are intended for use for custom purposes. They are real time signals.

Different signals

The following signals are not standardized by POSIX, but are sometimes used on some systems.

SIGEMT

The EMT signal is sent in-process when an emulator interrupt occurs.

SIGINFO

The INFO signal is sent in progress when a status request is received from the control terminal.

SIGPWR

The PWR signal is sent in process when the system experiences a power failure.

SIGLOST

The LOST signal is sent to a process when a "file lock" is lost.

SIGWINCH

The WINCH signal is sent to a process when its control terminal changes its size.

Sending signals from the keyboard

Signals can be sent from the keyboard. Several standard default values ​​are listed below. By default, the keyboard shortcuts for sending interrupt signals can be defined using the stty command.

CTRL-C

Send SIGINT (interrupt). By default this causes the process to terminate.

CTRL-Z

Send SIGTSTP (Suspend). By default, this causes the process to suspend all operations.

CTRL-\

Send SIGQUIT (Quit). By default, this causes the process to terminate immediately and reset the kernel.

CTRL-T

Send SIGINFO (INFO). By default, this causes the operating system to display information about the command. Not supported on all systems.

conclusion

When applications misbehave and cause the system to freeze, it is very tempting to restart your computer and start the session all over again. With these "kill" commands, you can better manage bad behavior of applications that cause or may cause a system crash. With this, I conclude this topic “The kill command in Unix/Linux”.

Be that as it may, sooner or later we are faced with the need to kill a buggy or hung process in Linux. Yes, yes, some applications in Linux sometimes freeze, despite their stability. It is in these cases that a wonderful utility will come in handy Kill. Let's figure out how to use this utility.

Each process in Linux has its own identifier called PID. Before stopping a process, you need to define it PID. The bottom line is that we need to find this identifier, let's open, for example, any program and try to find its identifier.

Hung process ID

To search we need commands ps and grep. Team ps- will display for us a list of active processes in the system and information about them, and the command grep- will search the results of the command ps. So let's open a terminal ( ctrl+alt+t) and look at the active processes

p.s. axu

As you have already noticed, the list is very large and scrolling through it to find the process we need is a waste of time, for this we will use a wonderful program grep. To find the process we need, after entering grep, specify the application we are looking for. Using Viber as an example, it looks like this:

p.s. | grep viber pol 22685 0.0 1.9 647748 76620 ? Sl 13:01 0:04 /usr/bin/python /usr/bin/viberwrapper-indicator pol 22697 3.0 5.4 5402084 216120 ? Sl 13:01 4:52 /opt/viber/Viber pol 24068 0.0 0.0 17192 2216 pts/0 S+ 15:41 0:00 grep --color=auto viber

In the first line running application viberwrapper-indicator, you can read about this application. The second line is Viber itself, which we will “extinguish” today, but what is the third line? The third process is the process itself grep, since we specified the word viber as a search parameter, and grep found itself in the command output ps.

There is another easier way to find out PID process is a command pidof, which takes the process name as a parameter and outputs its PID. Be careful about case, if the process name starts with a capital letter, and you write it with a small letter (or vice versa), then pidof will not be there

pidof Viber

As you already noticed, I was given 3 lines with the active Viber application

Completion of the process or, more simply put, “Murder”

Now we know the Viber process ID and we have the opportunity to “Kill” it:

kill 22697

In general, the kill command is intended to send a signal to a process. By default, if we do not specify any attributes, the SIGTERM signal (from the word termination) is sent. SIGTERM tells the process to terminate. Each signal has its own number. SIGTERM is numbered 15. A list of all signals (and their numbers) that the command can send kill, can be derived by running kill -l. To send the SIGKILL signal (numbered 9) to process 22697, run on the command line:

kill -9 22697

The SIGTERM signal may not stop the process (for example, if the signal is intercepted or blocked), but SIGKILL always kills the process, since it cannot be intercepted or ignored.
Look full list attributes can be done by running the command

kill -l

Tasks and processes

Anything performed in Linux program called process. Linux as a multitasking system is characterized by the fact that many processes belonging to one or more users can be executed simultaneously. You can display a list of processes currently running using the command ps, for example, as follows:

/home/larry# ps PID TT STAT TIME COMMAND 24 3 S 0:03 (bash) 161 3 R 0:00 ps /home/larry#

Please note that by default the command ps displays a list only of those processes that belong to the user who launched it. To view all processes running in the system, you need to issue the command ps -a . Process numbers(process ID, or PID), listed in the first column, are unique numbers that the system assigns to each running process. The last column, headed COMMAND, indicates the name of the command being run. In this case, the list contains processes launched by the user larry himself. There are many other processes running in the system; their full list can be viewed with the command ps-aux. However, among the commands run by user larry, there is only bash (the command shell for user larry) and the command itself ps. The bash shell can be seen running concurrently with the command ps. When the user entered the command ps, the bash shell started executing it. After the team ps has finished its work (the process table is displayed), control returns to the bash process. Then the bash shell displays a prompt and waits for a new command.

A running process is also called task(job). The terms process and task are used interchangeably. However, usually a process is called a task when it means job management(job control). Job control is a command shell feature that gives the user the ability to switch between multiple jobs.

In most cases, users will only run one task - this will be the last command they entered in the command shell. However, many shells (including bash and tcsh) have functions job management(job control), allowing you to run several commands at the same time or tasks(jobs) and, as needed, switch between them.

Job management can be useful if, for example, you are editing a large text file and want to temporarily interrupt editing to do some other operation. You can use the job management features to temporarily leave the editor, return to the shell prompt, and perform other actions. When they are done, you can return back to working with the editor and find it in the same state in which it was left. There are many more useful uses for job management functions.

Foreground and background mode

Tasks can be either foreground(foreground), or background(background). There can only be one task in the foreground at any given time. The foreground task is the task with which you are interacting; it receives input from the keyboard and sends output to the screen (unless, of course, you redirected the input or output somewhere else). Against, background jobs do not receive input from the terminal; Typically, such jobs do not require user interaction.

Some tasks take a very long time to complete, and nothing interesting happens while they are running. An example of such tasks is compiling programs, as well as compressing large files. There's no reason to stare at the screen and wait for these tasks to complete. Such jobs should be run in the background. During this time, you can work with other programs.

To control the execution of processes in Linux, a transfer mechanism is provided signals. A signal is the ability of processes to exchange standard short messages directly using the system. The signal message does not contain any information except the signal number (for convenience, a name predefined by the system can be used instead of a number). In order to transmit a signal, a process only needs to use a system call kill(), and in order to receive the signal, you don’t need anything. If a process needs to respond to a signal in some special way, it can register handler, and if there is no handler, the system will react for it. Typically, this causes the process that received the signal to terminate immediately. The signal handler starts asynchronously, immediately upon receiving the signal, no matter what the process is doing at the time.

Two signals - number 9 ( KILL) and 19 ( STOP) - always processed by the system. The first of them is needed in order to kill the process for sure (hence the name). Signal STOP suspends process: in this state, the process is not removed from the process table, but is not executed until it receives signal 18 ( CONT) - after which it will continue to work. In the Linux command shell, the signal STOP can be passed to the active process using an escape sequence Ctrl -Z .

Signal number 15 ( TERM) serves to interrupt the job. At interruption(interrupt) job process dies. Jobs are usually interrupted by an escape sequence Ctrl -C. There is no way to restore an interrupted job. You should also be aware that some programs intercept the signal TERM(using a handler), so that pressing a key combination Ctrl -C(o) may not abort the process immediately. This is done so that the program can destroy traces of its work before it is completed. In practice, some programs cannot be interrupted in this way at all.

Transferring to background and destroying jobs

Let's start with simple example. Let's look at the yes command, which at first glance may seem useless. This command sends an endless stream of strings consisting of the character y to standard output. Let's see how this command works:

/home/larry# yes y y y y y

The sequence of such lines will continue indefinitely. You can destroy this process by sending it an interrupt signal, i.e. by pressing Ctrl -C. Let's do things differently now. To prevent this endless sequence from being displayed on the screen, we will redirect the standard output of the yes command to /dev/null . As you may know, the /dev/null device acts as a "black hole": all data sent to this device is lost. Using this device it is very convenient to get rid of too much output from some programs.

/home/larry# yes > /dev/null

Now nothing is displayed on the screen. However, the shell prompt is also not returned. This is because the yes command is still running and sending its messages consisting of the letters y to /dev/null . You can also destroy this task by sending it an interrupt signal.

Now let's say you want the yes command to continue to work, but also to return the shell prompt to the screen so that you can work with other programs. To do this, you can translate the yes command to background mode, and she will work there without communicating with you.

One way to put a process into the background is to append an & to the end of the command. Example:

/home/larry# yes > /dev/null & + 164 /home/larry#

The message is job number(job number) for the process yes. The command shell assigns a job number to each job it runs. Since yes is the only executable job, it is assigned the number 1. The number 164 is the identification number associated with this process (PID), and this number is also given to the process by the system. As we will see later, a process can be accessed by specifying both of these numbers.

So now we have a yes process running in the background, continuously sending a stream of y's to the /dev/null device. In order to find out the status of this process, you need to execute the command jobs, which is a shell internal command.

/home/larry# jobs + Running yes >/dev/null & /home/larry#

We see that this program really works. In order to find out the status of a task, you can also use the command ps, as shown above.

In order to transmit a signal to the process (most often there is a need interrupt job job) the utility is used kill. This command is given either a job number or a PID as an argument. An optional parameter is the number of the signal that needs to be sent to the process. By default the signal is sent TERM. In the above case, the job number was 1, so the command kill %1 will interrupt the job. When a job is accessed by its number (rather than its PID), then before that number in command line you need to put the percent symbol (“%”).

Now let's enter the command jobs again to check the result of the previous action:

/home/larry# jobs Terminated yes >/dev/null

In fact, the job is destroyed, and the next time you enter the jobs command, there will be no information about it on the screen.

You can also kill a job using the process identification number (PID). This number, along with the job identification number, is indicated when the job starts. In our example, the PID value was 164, so the command kill 164 would be equivalent to the command kill %1. When using PID as an argument to the kill command, you do not need to enter the "%" character.

Pausing and resuming jobs

Let's first start the process with the yes command in the foreground, as was done before:

/home/larry# yes > /dev/null

As before, because the process is running in the foreground, the shell prompt does not return to the screen.

Now, instead of interrupting the task with a key combination Ctrl -C, the task is possible suspend(suspend, literally - to suspend), sending him a signal STOP. To pause a task, you need to press the appropriate key combination, usually this Ctrl -Z .

/home/larry# yes > /dev/null Ctrl -Z+ Stopped yes >/dev/null /home/larry#

The suspended process simply does not execute. It does not consume processor resources. A suspended task can be started to run from the same point as if it had not been suspended.

To resume the job running in the foreground, you can use the command fg(from the word foreground - foreground).

/home/larry# fg yes >/dev/null

The command shell will once again display the command name so that the user knows which task he is in. this moment launched in the foreground. Let's pause this task again by pressing the keys Ctrl -Z, but this time let's launch it into the background with the command bg(from the word background - background). This will cause the process to run as if it had been run using a command with an & at the end (as was done in the previous section):

/home/larry# bg + yes $>$/dev/null & /home/larry#

The shell prompt is returned. Now the team jobs must show that the process yes is actually working at the moment; this process can be killed with the command kill, as it was done before.

You cannot use the keyboard shortcut to pause a task running in the background Ctrl -Z. Before pausing a job, it must be brought to the foreground with the command fg and only then stop. Thus, the command fg can be applied to either suspended jobs or to a job running in the background.

There is a big difference between background jobs and suspended jobs. A suspended job does not run - it does not consume processor power. This job does not perform any action. A suspended task occupies a certain amount of computer RAM; after some time, the kernel will pump out this part of the memory to HDD « poste restante" In contrast, a background job is running, using memory, and doing some things you might want to do, but you may be working on other programs at the same time.

Jobs running in the background may attempt to display some text on the screen. This will interfere with working on other tasks.

/home/larry# yes &

Here the standard output has not been redirected to the /dev/null device, so an endless stream of y characters will be printed to the screen. This thread cannot be stopped because the key combination Ctrl -C does not affect jobs in the background. In order to stop this output, you need to use the command fg, which will bring the task to the foreground, and then destroy the task with a key combination Ctrl -C .

Let's make one more remark. Usually by team fg and the team bg affect those jobs that were most recently suspended (these jobs will be marked with a + symbol next to the job number if you enter the command jobs). If one or more jobs are running at the same time, jobs can be placed in the foreground or background by specifying commands as arguments fg or commands bg their identification number (job ID). For example, the command fg %2 puts job number 2 to the front and the command bg %3 puts job number 3 in the background. Use PIDs as command arguments fg And bg it is forbidden.

Moreover, to bring a job to the foreground, you can simply specify its number. Yes, team %2 will be equivalent to the command fg %2 .

It is important to remember that the job control function belongs to the shell. Teams fg , bg And jobs are internal teams shells. If, for some reason, you are using a command shell that does not support job management functions, then you will not find these (and similar) commands in it.



tell friends