The shutdown command in linux

5 Linux Commands to Shutdown and Reboot the System

Linux shutdown / reboot command

On Linux, like all tasks, the shutdown and restart operations can also be done from the command line.

The commands are shutdown, halt, poweroff, reboot and REISUB keystrokes.

In this post I am going to show you how to shutdown or restart a linux system using these commands.

The commands are useful specially when you have to reboot a remote linux server, where only shell access is available and no gui.

Servers often need a restart when upgrades are installed or need to shutdown for other maintainance tasks.

The commands are available on any linux system like centos, ubuntu, debian, fedora or suse and do not require the installation of any extra packages.

1. «shutdown» command

The first command is the shutdown command and it can be used to shutdown a system or restart it. It is commonly used to shutdown or reboot both local and remote machines.

To shutdown a machine call the shutdown command like this

The h option is for halt which means to stop. The second parameter is the time parameter. «now» means that shutdown the system right away.

The time parameter can be specified in minutes or hours also. For example

The above command shall flash the message to all other logged in users and give them 5 minutes before the system goes for shutdown.

The shutdown command can be used to restart a system with the r option instead of the h option. Usage is same as before. Just replace the h option with r option.

All other logged in users will see a broadcast message in their terminal like this

At this point a shutdown can be cancelled by calling shutdown with «c» option.

2. «reboot» command

Next command is the reboot command. It can be used to shutdown or reboot linux.

The following command will shutdown linux.

The «p» options stands for poweroff.

To reboot linux just call the reboot command directly without any options.

This will perform a graceful shutdown and restart of the machine. This is what happens when you click restart from your menu.

Reboot linux forcibly

The following command will forcefully reboot the machine. This is similar to pressing the power button of the CPU. No shutdown takes place. The system will reset instantly.

The man page explains it as follows

3. «halt» command

The next command is the halt command. This can shutdown a system

The halt command also has a force option, but you do not want to use it. It is supposed to shutdown the system instantly. But its behaviour may not be consistent. Desktops might hang on running this command.

4. «poweroff» command

There is another command exactly same as the halt command. It does the same things and takes the same options.

5. REISUB — R E I S U B key strokes

The above shown commands can be used when you are in control of your system. What if the system has hanged and is not responding at all. And you do not want to press the power button on the CPU which might lead to data corruption. To save from such a situation, comes the magic sysRQ keys.

A special combination of key presses that will allow you to reboot your linux system, no matter how much it is hanged. Check the wikipedia article. for more information.

Warning : Pressing the following keys would instantly reboot your system. Its similar to pressing the power button of your CPU or executing the reboot -f command.

Now in place of the B key we have to use R E I S U letters first. Each key does a task as mentioned below

1. Hold down the Alt and SysRq (Print Screen) keys.
2. While holding those down, type the following keys in order, several seconds apart: R E I S U B
3. Computer should reboot.

Make sure to have some time gap between each of keys R E I S U B.

The sysrq feature can be controlled by changing the value of /proc/sys/kernel/sysrq. To check if sysrq is enabled on the system or not, echo the value. It should be non zero.

Читайте также:  Где находится папка с темами для windows

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .

10 thoughts on “ 5 Linux Commands to Shutdown and Reboot the System ”

It worked on SUSE SLES 11

Now systemctl utility replaces a number of power management commands and even the shutdown command will call systemctl utility to perform the shutdown tasks.

The command reboot does work and immediately rebooted my Bluestar Linux system 4.20.7 (based on Arch Linux).

I am so glad that you could reboot your linux system!

If I’m not mistaken, reboot by itself actually does a shutdown: https://linux.die.net/man/8/reboot . You have to do reboot -f to actually get it to reboot.

Arrrgh so sick of finding the incorrect example of shutdown everywhere. The reboot syntax shown, on Ubuntu and probably in every flavor today, will Immediately reboot your server with no delay or warning. the +5 option is either wrong or in the wrong spot.

Important note – this only applies (AFAIKT) to x86 systems. On arm – no-worky.

what? 20 – 30 mins? O.o Shouldn’t it be 20 – 30 seconds?

I rebooted my linux machine using command reboot -f, it went down. How long does it takes normally to start again?

Its depends upon hardware and file system mounted on Linux box , If it is high end hardware and have been mounted more file system then it will 20-30 mins to come online

Источник

Linux shutdown command

On Unix-like operating systems, the shutdown command shuts down or reboots the system.

Description

The shutdown command brings the system down in a secure way. All logged-in users are notified that the system is going down, and login operations are blocked. It is possible to shut the system down immediately, or after a specified delay.

All processes are first notified that the system is going down by the signal SIGTERM. This gives programs like vi time to save the file being edited, mail and news processing programs a chance to exit cleanly, etc.

shutdown does its job by signalling the init process, asking it to change the runlevel. Runlevel 0 is used to halt the system, runlevel 6 is used to reboot the system, and runlevel 1 is used to put the system into a state where administrative tasks can be performed (single-user mode). Runlevel 1 is the default, unless the -h or -r options are specified.

Your system may have a different set of options for the shutdown command; check your documentation for details.

Syntax

Options

-a Control access to the shutdown command using the control access file /etc/shutdown.allow. See Access Control below for more information.
-k Do not shut down, but send the warning messages as if the shutdown were real.
-r Reboot after shutdown.
-h Instructs the system to shut down and then halt.
-P Instructs the system to shut down and then power down.
-H If -h is also specified, this option instructs the system to drop into boot monitor on systems that support it.
-f Skip fsck after reboot.
-F Force fsck after reboot.
-n Don’t call init to do the shutdown of processes; instruct shutdown to do that itself.

The use of this option is discouraged, and its results are not always predictable. -c Cancel a pending shutdown. (This does not apply to «shutdown now«, which does not wait before shutting down.) With this option, it is not possible to give the time argument, but you can still specify an explanatory message that will be sent to all users. -t sec Tell init to wait sec seconds between sending processes the warning and the kill signal, before changing to another runlevel. time The time argument specifies when to perform the shutdown operation.

The time can be formatted in different ways:

First, it can be an absolute time in the format hh:mm, in which hh is the hour (1 or 2 digits, from 0 to 23) and mm is the minute of the hour (in two digits).

Second, it can be in the format +m, in which m is the number of minutes to wait.

Also, the word now is the same as specifying +0; it shuts the system down immediately. message A message to be sent to all users, along with the standard shutdown notification.

Details

If a shutdown is scheduled for the future, it will create the advisory file /etc/nologin which causes programs such as login not to allow new user logins. This file is created five minutes before the shutdown sequence starts. shutdown removes this file if it is stopped before it can signal init (i.e. it is cancelled or something goes wrong). It also removes it before calling init to change the runlevel.

The -f flag means «reboot fast». This only creates an advisory file /fastboot which can be tested by the system when it comes up again. The system boot rc file («rc» stands for «runcom», which is short for «run commands») can test if this file is present, and decide not to run fsck since the system has been shut down in the proper way. After that, the boot process should remove /fastboot.

The -F flag means «force fsck«. This only creates an advisory file /forcefsck which can be tested by the system when it comes up again. The boot rc file can test if this file is present, and decide to run fsck with a special «force» flag so that even properly unmounted file systems get checked. After that, the boot process should remove /forcefsck.

The -n flag causes shutdown not to call init, but to kill all running processes itself. shutdown will then turn off quota, accounting, and swapping and unmount all file systems.

Access Control

shutdown can be called from init when the Ctrl+Alt+Del key combination is pressed, if there exists an appropriate entry in /etc/inittab. This would mean that everyone who has physical access to the console keyboard can shut the system down, however.

To prevent this, shutdown can check to see if an authorized user is logged in. If shutdown is called with the -a argument (add this to the invocation of shutdown in /etc/inittab), it checks to see if the file /etc/shutdown.allow is present. It then compares the login names in that file with the list of people that are logged in on a virtual console (from /var/run/utmp). Only if one of those authorized users or root is logged in, it will proceed. Otherwise, it will write the message

. to the (physical) system console. The format of /etc/shutdown.allow is one username per line. Empty lines and comment lines (prefixed by a #) are allowed. Currently there is a limit of 32 users in this file.

Note that if /etc/shutdown.allow is not present, the -a argument is ignored.

Halting vs. Powering Off

The -H option just sets the init environment variable INIT_HALT to HALT, and the -P option just sets that variable to POWEROFF. The shutdown script that calls halt as the last thing in the shutdown sequence should check these environment variables and call halt with the right options for these options to actually have any effect.

Files

/fastboot
/etc/inittab
/etc/init.d/halt
/etc/init.d/reboot
/etc/shutdown.allow

Examples

Schedule the system to shut down at 8 A.M.

Schedule the system to shut down at 8 P.M.

Schedule the system to shut down in fifteen minutes. Along with the normal message alerting users that the system is shutting down, they will be given the descriptive message about a hardware upgrade.

Bring down the system immediately.

Bring down the system immediately, and automatically reboot it.

Bring down the system immediately, and automatically power off the system.

halt — Stop the computer.
poweroff — Stop the computer.
reboot — Stop the computer.
wall — Send a message to all logged-in users.

Источник

Выключение Linux из командной строки

Выключение компьютера — действие, с которым обычные пользователи сталкиваются чуть ли не каждый день. Если выключать сервер приходится довольно редко, то обычные, десктопные компьютеры подвержены этой операции очень даже часто. Большинство пользователей выключают linux в графическом интерфейсе системы. В окружении рабочего стола KDE это делается через главное меню, а в Gnome и Unity даже есть специальная кнопка на панели для решения этой задачи.

Но не всегда есть возможность выключить компьютер linux таким образом. Например, если окружение рабочего стола не работает, то больше ничего не остается, кроме того, чтобы выполнять выключение компьютера из командной строки. К тому же выключение компьютера linux через терминал единственно возможный способ для серверов, где нет графического интерфейса. Как вы увидите, этот способ также намного гибче обычного выключения, поскольку вы можете настроить нужное время отключения, или же выключить компьютер, дождавшись завершения работы определенной программы.

Процесс выключения Linux

Часто для выключения Linux из терминала используется утилита shutdown. Есть также команды poweroff, halt, но они для нестандартных случаев. Также выключить linux из консоли можно с помощью сочетаний клавиш SysRQ. Но сначала давайте рассмотрим синтаксис команды shutdown. Естественно, команда shutdown в Linux или любая другая не самостоятельно завершает работу системы и выключает компьютер. Она всего лишь передает запрос на выключение системе инициализации, а затем ядру. А уже они выполняют ряд сложных операций по подготовке и выключению компьютера. Если кратко, то вот они:

  • Завершение процессов пользователя.
  • Сигнал SIGTERM всем процессам.
  • Сигнал SIGKILL всем процессам.
  • Монтирование файловых систем в режиме только для чтения.
  • Подготовка внешних устройств к отключению.
  • Блокировка пространства пользователя, чтобы гарантировать, что ни один код пользователя больше не будет запущен.
  • Завершение работы и отключение питания большинства периферических устройств.
  • Отключение питания компьютера.

Теперь вы понимаете суть процесса выключения и то почему нельзя просто выдернуть шнур питания с розетки. Если это сделать, компьютер отключится моментально и не выполнит всех необходимых операций, а это может грозить потерей не сохраненных или даже недавно сохраненных данных, повреждением файловой системы и т д. Поэтому желательно выключать компьютер правильно с помощью shutdown или других специальных утилит.

Синтаксис и опции shutdown

Синтаксис команды очень простой:

$ shutdown [опции] [время] [сообщение]

Опции задают параметры отключения, их мы рассмотрим ниже. Время можно задавать в виде чч:мм в 24 часовом формате. Также можно использовать запись +минуты, указывающую через сколько минут от текущего момента нужно выключить компьютер с Linux. Также доступна константа now, указывающая, что выключать нужно прямо сейчас. Параметр сообщение позволяет задать сообщение, которое будет выведено в терминал перед выключением.

Вот основные опции утилиты:

  • —help — вывести справку по программе
  • -H, —halt — отключить питание, не завершая процессы и не перемонтируя файловые системы
  • -P, —poweroff — нормальное выключение
  • -r, —reboot — перезагрузка
  • -k — не выполнять реальных действий, а только вывести сообщение
  • —no-wall — выключить компьютер, но не выводить сообщение
  • -c — отменить запланированное выключение linux из командной строки

Вот в принципе и все опции утилиты, их больше чем достаточно для такого простого действия. Теперь можно переходить к примерам, но сначала давайте рассмотрим, что же происходит во время включения Linux.

Выключение компьютера в Linux

1. shutdown

Самая простая и самая часто используемая команда выключения компьютера linux, отключит компьютер немедленно:

sudo shutdown -h now

Как видите, используется обычное выключение, и константа времени now, тоесть сейчас.

Теперь попробуем запланировать выключение компьютера linux через пять минут:

sudo shutdown -h +5 «Компьютер будет выключен через 5 минут»

Мы запланировали вывод сообщения перед выключением. Чтобы отменить команду shutdown выполните:

sudo shutdown -c

Точно так же мы можем указать точное время выключения, например в девять вечера:

sudo shutdown -h 21:00

Как я уже говорил, не только команда shutdown linux умеет выключать компьютер, есть еще несколько утилит способных на это. Рассмотрим их тоже.

2. reboot

Команда reboot обычно используется для перезагрузки системы, но она также умеет выключать компьютер. Мы не будем ее подробно рассматривать, потому, что она еще проще команды shutdown. Для выключения нужно задать опцию -p:

3. halt

Эта команда тоже выключает компьютер. Только делает она это очень по-своему. Она не выполняет никаких подготовительных действий перед выключением, а просто отключает питание:

Использование halt может повредить систему

4. poweroff

Это аналог halt, делает в точности то же самое:

5. SysRQ

Помните, в начале статьи, я говорил о сочетании клавиш для включения компьютера? Рассмотрим этот вопрос подробнее.

SysRQ — это подсистема, реализованная на уровне ядра. Ядро обрабатывает все нажатия клавиш, а с помощью этой подсистемы, оно может принимать от пользователя команды, даже когда система полностью зависла. Основное предназначение этой подсистемы — работа с компьютером в проблемных ситуациях, например, если вы думаете что ваш компьютер заразил вирус, или компьютер завис и его нужно выключить. Для доступа к SysRq используются сочетания клавиш Alt+PrtScr+номер

Самое интересное, что мы можем выполнить безопасное выключение компьютера linux. Для этого зажмите клавиши Alt + PrtScr и поочередно нажимайте:

  • R — разблокировать клавиатуру;
  • E — послать всем процессам сигнал SIGTERM;
  • I — послать всем процессам сигнал SIGKILL;
  • S — перенести все данные из кеша файловых систем на диск;
  • U — перемонтировать файловые системы только для чтения;
  • B — перезагрузить.

Также вместо всего этого можно воспользоваться сочетанием клавиш Alt+PrtScr+O, в таком случае, вся процедура будет выполнена автоматически, эта команда поддерживается не всеми ядрами.

6. Графический интерфейс

Выключить компьютер в графическом интерфейсе ещё проще. Для этого кликните по иконке выключения в правом верхнем углу, а затем выберите Выключить/Завершить сеанс, затем Выключение.. и снова Выключить:

Выводы

Теперь вы знаете все что нужно, о том, как выключить Linux через терминал. Если вас застигнет врасплох ошибка или зависание компьютера, вы знаете что делать. Если остались вопросы — пишите в комментариях!

Источник

Читайте также:  Csr bluetooth drivers windows 10
Оцените статью