Linux stop all processes user

How to Kill all Processes for a User in Linux

In this tutorial, we shall discuss how to find and kill processes from a specific user. We will use tools such as pkill and killall.

NOTE: Ensure you have access to an administrative account or the root account because regular users can only kill their processes, not processes belonging to other users. On the other hand, the root user can kill all processes.

Let us get started.

Understanding System Signals

To kill a specific process, the command sends a signal to the process. By default, kill commands such as killall send a TERM signal that gracefully stops the specified process.

Before we proceed to kill command, let us take a brief overview of the process signals.

The common types of kill signals include:

  • SIGHUP – This signal reloads a process. It has an integer value of 1.
  • SIGINT – Interrupt from the keyboard such as CTRL + C. It has an integer value of 2.
  • SIGKILL – Kill a process. It has an integer value of 9.
  • SIGTERM – This is a termination signal, which, as stated, gracefully stops a process. It has an integer value of 15.
  • SIGSTOP – Stops a process. It has an integer value of either 17, 19, or 23.

NOTE: When terminating processes, it is good to start with the least aggressive signal, such as TERM. Using a signal such as TERM will allow the program to shut down correctly and use the set measures when the program receives the TERM signal.

A KILL signal can also be helpful, especially if a process has encountered an error, fails to exit or does not respond to the INT signal.

To view all the available signals, use a command such as a kill -l

Method #1 – The Killall Command

The first command you can use to kill Linux processes is the killall command. For this, you need the PID value or the name of the process you wish to terminate.

You can use a tool such as pgrep to get the PID of a specific process.

Once you have the PID value of the process, you can terminate using the kill command as:

$ killall -15 2500

$ killall -15 bash

The command above will send a graceful termination signal.

To send a KILL signal, use the -9 integer as:

# or
$ killall -9 bash

How to kill all user processes with killall

Killall command allows you to terminate all the processes owned by a specific user. To do this, use the -u flag.

For example, to terminate all processes spawned by the ubuntu user.

CAUTION: Depending on the user specified in the command, terminating the processes can cause the system to crash or stop critical system processes. Therefore, before applying this command, ensure the user in question is not running processes you do not wish to terminate.

Method #2: The Pkill Command

Another great tool you can use to terminate Linux processes is the pkill command. This command works similarly to killall.

For example, to terminate the bash process with pkill, use the command:

To kill all processes owned by the ubuntu user, we can use the command:

Conclusion

That’s it for this one.

In this guide, we quickly discussed ways to terminate processes in Linux and various types of kill signals. As seen, killing a single process or multiple processes owned by a specific Linux user is easy.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list

Источник

Как убить все процессы пользователя в Linux

Как мы знаем, Linux — многопользовательская ОС, поэтому с каждым пользователем могут быть связаны его собственные процессы. Такое разделение существует в целях безопасности. Запуская ту или иную программу от имени непривилегированного пользователя, ОС снижает риски несанкционированного проникновения и риски повреждения системных файлов.

В этой статье мы расскажем о том, как завершить все запущенные процессы конкретного пользователя.

Как завершить все процессы пользователя?

Для начала сформируем перечень всех процессов всех пользователей. В терминале Linux выполним следующую команду:

Как видно на скриншоте, имеются процессы, связанные с тремя пользователями (root, mint1 и mint). Допустим, нам срочно понадобилось завершить все процессы пользователя mint1.

Здесь следует немного подробнее остановиться на самом понятии процесса в Linux. Процесс – программа, запущенная в виртуальном адресном пространстве. Каждый процесс имеет свой уникальный номер или идентификатор — PID (Process Identificator). Работая с процессами, операционная система идентифицирует процессы именно по PID.

Для того, чтобы убить ненужные процессы, достаточно убить все PID процессов конкретного пользователя (в данном случае mint1). Для этого можно просто скопировать номера идентификаторов этого пользователя и ввести следующую команду:

sudo kill -9 3501 4333

Однако, количество PID может быть куда больше двух. Да и выполнить все действия вообще-то тоже можно с помощью одной команды, умещающейся в одну строку.

Читайте также:  Картридж для принтера mf635cx canon

Например, используем конвейер и программу grep ( символ | обозначает передачу результатов выполнения первой команды второй команде по конвейеру):

ps au | grep -e ‘^mint1’

С помощью grep были выбраны все процессы пользователя mint1. Далее необходимо из второй колонки слева выбрать все PID. Сделаем это с помощью программы awk, добавив, соответственно, ещё один конвейер:

ps au | grep -e ‘^mint1’ | awk ‘

Теперь нужно убить полученные значения PID. Опять добавим конвейер (в данном и последующих примерах все команды выполняются от имени суперпользователя root) и выполним группу команд:

ps au | grep -e ‘^mint1’ | awk ‘‘ | xargs kill -9

С помощью такой конвейеризованной группы команд мы завершили все процессы пользователя mint1.

Подобный конвейер можно было бы сформировать и так:

ps aux | awk ‘/^mint1/ ‘ | xargs kill -9

Кроме того, для того, чтобы убить все процессы пользователя в Linux, можно воспользоваться также следующими командами:

killall -u mint1

Однако и это ещё не всё. Нужно ещё проверить наличие процессов, связанных с пользователем mint1, и их состояние. Сделаем это с помощью команды:

Как видите, процессы, связанные с пользователем mint1, отсутствуют. Способов убить все процессы пользователя в Linux достаточно много, мы показали лишь некоторые из них.

Источник

How to kill all processes run by a user on Linux

Last updated on September 15, 2020 by Dan Nanni

If you are a system administrator, there are situations where you want to kill all processes belonging to a specific user, for example because the user is being removed from the system, or the user is forking malicious processes or runaway daemons, etc. It will be cumbersome to kill individual processes of the user one by one manually.

In this tutorial, I will show how to kill all running processes launched by a user at once. Here, I will demonstrate several commands that kill all processes owned by Linux user xmodulo .

Method One: grep

The first method is to feed kill command with a list of process IDs generated by ps command.

Method Two: pgrep

A more convenient way to look up processes based on user name is to use pgrep .

Method Three: pkill

pkill can streamlines the whole process of looking up processes by user, and sending them signals. A default signal sent by pkill is SIGTERM . Using pkill , you can kill all processes by owner easily.

Method Four: killall

killall is very similar to pkill in terms of killing processes by user name.

Method Five: slay

A command line tool whose sole purpose is to kill processes by owner name is slay . It provides clean kill mode, where matched processes are first sent SIGTERM signal, and those that haven’t been terminated after 10 seconds are killed with SIGKILL signal. slay is available on Ubuntu or Debian. To install slay and use it:

Precaution: When using slay , pay particular attention to sudo or run it as root. If you by accident attempt to slay another user as non-root user, it will of course not work, and more importantly, slay will kill your own processes!

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Источник

Search Results

No Results

Filters

Use killall and kill Commands to Stop Processes on Linux

killall is a tool for terminating running processes on your system based on name. In contrast, kill terminates processes based on Process ID number (PID). kill and killall can also send specific system signals to processes.

Use killall and kill in conjunction with tools including Process Status, ps , to manage and end processes that have become stuck or unresponsive.

Throughout this guide, replace [process name] in each example with the name of the process you wish to terminate.

Usage

How to Use killall

The killall command takes the following form:

killall will terminate all programs that match the name specified. Without additional arguments, killall sends SIGTERM , or signal number 15, which terminates running processes that match the name specified. You may specify a different signal using the -s option as follows:

This sends the SIGKILL signal which is more successful at ending a particularly unruly processes. You may also specify signals in one of the following formats:

How to Use kill

The kill command terminates individual processes as specified by their PID.

Commands take the following form:

Without options, kill sends SIGTERM to the PID specified and asks the application or service to shut itself down. This is discussed further in the following section.

Multiple PIDs and alternate system signals can be specified within a single kill command. The following examples all send the SIGKILL signal to the PID specified:

System Signals

The kill command does not terminate a process directly. Rather, a signal is sent to the process where the process will have instructions to follow if it receives a given signal. The man pages provide further reference of all available signals:

To simply list all available signals without their descriptions:

If you need to convert a signal name into a signal number, or a signal number into a signal name, use the following as examples:

Find Running Processes

Use a utility like htop or top to view a real time list of process and their consumption of system resources.

Use the ps command to view processes that are currently running and their PIDs. The following example filters the list of all processes that are currently running for the string emacs using grep:

The number listed in the second column from the left is the PID, which is 3896 in the case of the emacs process. The grep process will always match itself for a simple search, as in the second result.

Once you have obtained the PID or process name, use killall or kill to terminate the process as above.

Another option to find the PID is though pgrep .

Verify Process Termination

Adding the -w option to a killall command causes killall to wait until the process terminates before exiting. Consider the following command:

This example issues the SIGTERM system signal to a background process with a name that matches irssi . killall will wait until the matched processes ends. If no process matches the name specified, killall returns an error message:

Читайте также:  Как удалить драйвера принтера canon на mac

This page was originally published on Monday, November 29, 2010.

Источник

10+ examples for killing a process in Linux

In this tutorial, we will talk about killing a process in Linux with multiple examples. In most cases, its as simple as typing kill command followed by the process ID (commonly abbreviated as PID).

As you can see, weve killed a process with the ID of 1813.

If you are a Windows user, it may help to think of the kill command as Linuxs equivalent of the End task button inside of the Windows task manager.

Table of Contents

List running processes

The ps -e command will list everything running on your system. Even with a minimal installation, the command will probably output more than 80 results, so its much easier to pipe the command to grep or more.

In the screenshot below, we check to see if SSH is running on the system.

This also gives us the PID of the SSH daemon, which is 1963.

Pipe to more if you want to look through your systems running processes one-by-one.

You can also make use of the top command in order to see a list of running processes. This is useful because it will show you how many system resources that each process is using.

The PID, User, and name of the resource are all identified here, which is useful if you decide to kill any of these services later.

Pay attention to the %CPU and %MEM columns, because if you notice an unimportant process chewing up valuable system resources, its probably beneficial to kill it!

Another very efficient away of obtaining the corresponding process ID is to use the pgrep command. The only argument you need to supply is the name (or part of the name) of the running process.

Heres what it looks like when we search for SSH. As you can see, it returns a process ID of 2506.

Kill a process by PID

Now that we know the PID of the SSH daemon, we can kill the process with the kill command.

You can issue a final ps command, just to ensure that the process was indeed killed.

The results come up empty, meaning that the process was shut down successfully. If you notice that the process is continuing to run — which should not normally happen — you can try sending a different kill signal to the process, as covered in the next session.

Note: Its not always necessary to use sudo or the root user account to end a process. In the former example, we were terminating the SSH daemon, which is run under the root user. Therefore, we must have the appropriate permissions to end the process.

Default signal sent by the kill command

By default, the kill command will send a SIGTERM signal to the process you specify.

This should allow the process to terminate gracefully, as SIGTERM will tell the process to perform its normal shutdown procedures — in other words, it doesnt force the process to end abruptly.

This is a good thing because we want our processes to shut down the way they are intended.

Sometimes, though, the SIGTERM signal isnt enough to kill a process. If you run the kill command and notice that the process is still running, the process may still be going through its shutdown process, or it may have become hung up entirely.

Force killing

To force the process to close and forego its normal shutdown, you can send a SIGKILL signal with the -9 switch, as shown here:

It can be tempting to always append the -9 switch on your kill commands since it always works. However, this isnt the recommended best practice. You should only use it on processes that are hung up and refusing to shut down properly.

When possible, use the default SIGTERM signal. This will prevent errors in the long run, since it gives the process a chance to close its log files, terminate any lingering connections, etc.

Apart from the SIGTERM and SIGKILL signals, there is a slew of other signals that kill can send to processes, all of which can be seen with the -l switch.

The numbers next to the names are what you would specify in your kill command. For example, kill -9 is SIGKILL, just like you see in the screenshot above.

For everyday operations, SIGTERM and SIGKILL are probably the only signals you will never need to use. Just keep the others in mind in case you have a weird circumstance where a process recommends terminating it with a different signal.

How to kill all processes by name?

You can also use the name of a running process, rather than the PID, with the pkill command. But beware, this will terminate all the processes running the under the specified name, since kill wont know which specific process you are trying to terminate.

Check out the example below, where we terminate five processes with a single pkill command.

In this example, we had wanted to only terminate one of those screen sessions; it wouldve been necessary to specify the PID and use the normal kill command. Otherwise, there is no way to uniquely specify the process that we wish to end.

How to kill all processes by a user?

You can also use the pkill command to terminate all processes that are running by a Linux user. First, to see what processes are running under a specific user, use the ps command with a -u switch.

That screenshot shows us that there are currently five services running under the user geek. If you need to terminate all of them quickly, you can do so with pkill.

How to kill a nohup process?

You can kill the nohup process the same way as any other running process. Note that you cant grep for nohup in the ps command, so youll need to search for the running process using the same methods as shown above.

Читайте также:  Как у принтера отключить проверку краски

In this example, we find a script titled test.sh which has been executed with the nohup command. As youll see, finding and ending it is much the same as the examples above.

The only difference with the output is that the shell notifies us that the process was terminated. Thats not part of kill, but rather a result from running the script in the background (the ampersand in this example) and being connected to the same tty from which the script was initiated.

How to run a process in the background?

The kill command is an efficient way to terminate processes you have running in the background. Youve already learned how to kill processes in this tutorial, but knowing how to run a process in the background is an effective combination for use with the kill command.

You can append an ampersand (&) to your command in order to have it executed in the background. This is useful for commands or scripts that will take a while to execute, and you wish to do other tasks in the meantime.

Here we have put a simple ls command into the background. Since its the type of command which takes very little time to execute, were given more output about it finishing its job directly after.

The output in our screenshot says Done, meaning that the job in the background has completed successfully. If you were to kill the job instead, it would show terminated in the output.

You can also move a job to the background by pressing Ctrl+Z on your keyboard. The ^Z in this screenshot indicates that we pressed Ctrl+Z and the test.sh script moved into the background.

You can see test.sh continuing to run in the background by issuing a ps command.

Using screen command

Another way to run a process in the background is to use the screen command. This works by creating what basically amounts to a separate terminal window (or screen and hence the name).

Each screen that you create has its process ID, which means that its an efficient way of creating background processes that can be later terminate using the kill command.

Screen command doesnt come with all Linux installs by default, so you may have to install it.

On Ubuntu and Debian-based distributions, you can install it with the following command:

Once you installed the screen command, you can create a new session by just typing screen.:

But, before you do that, its good to get in the habit of specifying names for your screens. That way, they are easy to look up and identify later. All you need in order to specify a name is the -S switch.

Lets make a screen called testing and then try to terminate it with the kill command. We start like this:

After typing this command and pressing enter, were instantly taken to our newly created screen. This is where you could start the process that you wish to have running in the background.

This is especially handy if you are SSHd into a server and need a process to continue running even after you disconnect.

With your command/script running, you can disconnect from the screen by pressing Ctrl+A, followed by D (release the Ctrl and A key before pressing the D key).

As you can see, the screen command has listed the process ID as soon as we detached the screen. Of course, we can terminate this screen (and the command/script running inside of it), by using the kill command.

You can easily look up the process ID of your screen sessions by using this command:

If we hadnt named our screen session by using the -S switch, only the process ID itself would be listed. To reattach to the any of the screens listed, you can use the -r switch:

In the screenshot below, we are killing the screen session we created (along with whatever is being run inside of it), and then issuing another screen -ls command in order to verify that the process has indeed ended.

How to kill a background process?

In one of our examples in the previous section, we put our tesh.sh script to run in the background. Most background processes, especially simple commands, will terminate without any hassle.

However, just like any process, one in the background may refuse to shut down easily. Our test.sh script has a PID of 2382, so well issue the following command:

In the screenshot, though, youll notice that the script has ignored our kill command:

As weve learned already, kill -9 is the best way to kill a process that is hung up or refusing to terminate.

How to kill stopped processes?

It can be useful to kill all your stopped background jobs at once if they have accumulated and are no longer useful to you. For the sake of example, were running three instances of our test.sh script in the background and theyve been stopped:

You can see these processes with the ps command:

Or, to just get a list of all the stopped jobs on the system, you can run the jobs command:

The easiest way to kill all the stopped jobs is with the following command:

Or use the -9 switch to make sure the jobs terminate immediately:

The `jobs -ps` command will list all jobs PIDs running in the background, which is why were able to combine its output with the kill command in order to end all the stopped processes.

Kill operation not permitted

If you are getting an operation not permitted error when trying to kill a process, its because you dont have the proper permissions. Either log in to the root account or use sudo (on Debian distributions) before your kill command.

I hope you find the tutorial useful. Keep coming back.

Источник

Поделиться с друзьями
КомпСовет
Adblock
detector