- Linux halt, poweroff and reboot commands
- Description
- Syntax
- Technical description
- Options
- Environment
- Files
- Examples
- Related commands
- 5 Linux Commands to Shutdown and Reboot the System
- Linux shutdown / reboot command
- 1. «shutdown» command
- 2. «reboot» command
- 3. «halt» command
- 4. «poweroff» command
- 5. REISUB — R E I S U B key strokes
- 10 thoughts on “ 5 Linux Commands to Shutdown and Reboot the System ”
- Linux halt system halted
- Примеры использования
- Прекращение работы центрального процессора
- Прекращение работы системы
- Перезагрузка системы
- Скрытное прекращение работы центрального процессора
- Зачем нужен halt?
Linux halt, poweroff and reboot commands
On Unix-like operating systems, the halt, poweroff, and reboot commands stop, power down, or reboot the system, respectively.
This page covers the GNU/Linux versions of halt, poweroff, and reboot.
Description
halt, poweroff, and reboot are commands you can run as root to stop the system hardware.
- halt instructs the hardware to stop all CPU functions.
- poweroff sends an ACPI signal which instructs the system to power down.
- reboot instructs the system to reboot.
These commands require superuser privileges. If you are not logged in as root, you need to prefix the command with sudo or the signal isn’t sent.
Syntax
Technical description
These programs allow a system administrator to reboot, halt or poweroff the system.
When called with —force or when in runlevel 0 or 6, this tool invokes the reboot system call itself (with REBOOTCOMMAND argument passed) and directly reboots the system. Otherwise, this invokes the shutdown tool with the appropriate arguments without passing REBOOTCOMMAND argument.
Before invoking reboot, a shutdown time record is first written to /var/log/wtmp
Options
-f, —force | Does not invoke shutdown and instead performs the actual action you would expect from the name. |
-p, —poweroff | Instructs the halt command to instead behave as poweroff. |
-w, —wtmp-only | Does not call shutdown or the reboot system call and instead only writes the shutdown record to /var/log/wtmp. |
—verbose | Outputs slightly more verbose messages when rebooting, which can be useful for debugging problems with shutdown. |
Environment
RUNLEVEL | reboot will read the current runlevel from this environment variable if set in preference to reading from /var/run/utmp. |
Files
/var/run/utmp | File where the current runlevel will be read from; this file also be updated with the runlevel record being replaced by a shutdown time record. |
/var/log/wtmp | A new runlevel record for the shutdown time will be appended to this file. |
Examples
If you are logged in as root, issuing the halt command will cease all CPU function on the system. On most systems, this will drop you into single-user mode and then power off the machine.
If you’re not logged in as root, prefix the halt command with sudo to run the command as the superuser.
If you are logged in as root, issuing the poweroff command sends an ACPI hardware signal which will instruct the system to commence with a complete and immediate shutdown. This is roughly equivalent to pressing the power button on a typical desktop computer.
Execute the poweroff command as root.
If you are logged in as root, issuing the reboot command will immediately initiate a reboot sequence. The system shuts down and then commence a warm boot.
Execute the reboot command as root.
Related commands
shutdown — Schedule a time for the system to be powered down.
Источник
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.
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 halt system halted
Команда halt предназначена для прекращения работы центрального процессора системы с отправкой сообщений всем ее пользователям. В большинстве случаев ее использование приводит к полному прекращению работы системы. Реализация функции, используемой посредством данной команды, зависит от архитектуры центрального процессора; например, в архитектуре x86 для этой цели предусмотрена специальная инструкция HLT. В текущее время эта команда является устаревшей, поэтому после перехода большинства дистрибутивов на менеджер инициализации systemd она была реализована в виде простой символьной ссылки на утилиту systemctl из состава systemd. Более того, в дистрибутивах Linux Mint, Ubuntu и Debian ее может не быть в системе по умолчанию. В таком случае при возникновении необходимости использования этой команды, а также таких команд, как reboot и shutdown, следует установить пакет программного обеспечения systemd-sysv с помощью следующей команды:
$ sudo apt-get install systemd-sysv
Базовый синтаксис команды выглядит следующим образом:
Утилита systemctl автоматически обрабатывает вызовы посредством символьной ссылки с именем halt и поддерживает параметры соответствующей утилиты для совместимости.
Наиболее важными параметрами являются параметры —poweroff и —reboot, позволяющие выключить и перезагрузить систему соответственно, параметр —force, предназначенный для принудительного прекращения работы центрального процессора путем осуществления системного вызова без подготовки системы, параметр —wtmp-only, позволяющий добавить запись в файл журнала /var/log/wtmp и не прекращать работу центрального процессора, параметр —no-wtmp, позволяющий прекратить работу центрального процессора без добавления записи в файл журнала /var/log/wtmp, а также параметр —no-wall, позволяющий не отправлять сообщение о прекращении работы центрального процессора всем пользователям системы.
Что касается утилиты systemctl, то она осуществляет изоляцию цели halt.target (то есть, достижение этой цели и закрытие всех остальных целей), в ходе которой осуществляется системный вызов reboot(RB_HALT_SYSTEM). Если вы не хотите использовать команду halt, вы можете воспользоваться одной из следующих команд:
$ sudo systemctl isolate halt.target
$ sudo systemctl halt
Они работают аналогичным образом.
Примеры использования
Прекращение работы центрального процессора
Для прекращения работы центрального процессора системы достаточно использовать команду halt без каких-либо параметров:
В результате работа центрального процессора системы должна завершиться.
Прекращение работы системы
Для более корректного прекращения работы системы следует использовать команду halt с параметром —shutdown:
$ sudo halt —shutdown
В этом случае прекращение работы системы будет осуществляться посредством подсистемы ACPI.
Перезагрузка системы
Для перезагрузки системы следует использовать команду halt с параметром —reboot:
$ sudo halt reboot
В результате система будет перезагружена.
Скрытное прекращение работы центрального процессора
Для того, чтобы прекратить работу центрального процессора без добавления записи в файл журнала /var/log/wtmp и отправки сообщения всем пользователям системы достаточно использовать параметры —no-wtmp и —no-wall:
$ sudo halt —no-wtmp —no-wall
В результате работа центрального процессора системы будет прекращена без лишних сообщений.
Источник
Зачем нужен halt?
Зачем нужен halt, когда есть poweroff?
На просторах интернета встретилось такое объяснение, что при выполнении halt, после того, как система выключена, можно вручную сделать ребут или выключить питание компа, нажав на кнопку.
Зачем это нужно, когда можно сразу сделать poweroff или reboot?
Приведите, пожалуйста, примеры реального использования halt.
Вывод сообщения об ошибке ядра, типа кернелпаника, когда ребут нежелателен, например. В embedded всяких, где ребута нет вообще, а ресет юзать не комильфо в данной ситуации.
зачем нужен halt или poweroff когда есть init?
Применительно к systemd:
А, ну с systemd как — хз. У меня halt всегда запускается и halt просто выключает компьютер напрочь, как и poweroff. Но, может, у кого-то по-другому работает?
Зачем нужен halt, когда есть poweroff?
у меня нет poweroff
Раньше надо было самому кнопку тыкать. видимо с тех пор и.
Раньше надо было самому кнопку тыкать. видимо с тех пор и.
А, ну точно. На AT кнопку надо было нажимать руками.
это как-то отменяет того, что в OpenBSD нет poweroff? я гашу систему с помощью halt -p — я уже привык, и в дебиане её так же гашу
Не отменяет, конечно. Я имел ввиду halt, который halt, т.е. просто выключает систему, но не выключает питание. Просто привел свою конфигурацию компа.
а вот теперь у меня хотелка появилась — как мне в моём bash’е сделать эти стрелочки без всяких user@home$ как щас?
Зачем нужен halt, когда есть poweroff?
Первые компьютеры не умели выключаться программно, потому не было poweroff, а теперь это симлинк на дань традиции к halt. Хотя halt — это инструкция процессора, когда он останавливается до немаскируемого прерывания, что иногда полезно, когда ядро упало, но информация осталась — panic=синий экран это оно.
Не отменяет, конечно. Я имел ввиду halt, который halt, т.е. просто выключает систему, но не выключает питание. Просто привел свою конфигурацию компа.
Но у тебя как работает? halt не выключает, а poweroff выключает питание? У меня вот оба выключают питание. Если даже смотреть man, то утверждается, что poweroff выключить питание (это то же самое, что и halt -p). Но на практике у меня оба без ключей отключают питание, хотя я встречал случаи компов или ноутов, когда вроде бы выключение питания не выключало его, а компы оставались висеть в строчке что-то типа system halted, но не выключались.
Источник