3 commands to reboot Linux (plus 4 more ways to do it safely)
Linux is fully capable of running not weeks, but years, without a reboot. In some industries, that’s exactly what Linux does, thanks to advances like kpatch and kgraph.
For laptop and desktop users, though, that metric is a little extreme. While it may not be a day-to-day reality, it’s at least a weekly reality that sometimes you have a good reason to reboot your machine. And for a system that doesn’t need rebooting often, Linux offers plenty of choices for when it’s time to start over.
Understand your options
Before continuing though, a note on rebooting. Rebooting is a unique process on each operating system. Even within POSIX systems, the commands to power down and reboot may behave differently due to different initialization systems or command designs.
Despite this factor, two concepts are vital. First, rebooting is rarely requisite on a POSIX system. Your Linux machine can operate for weeks or months at a time without a reboot if that’s what you need. There’s no need to «freshen up» your computer with a reboot unless specifically advised to do so by a software installer or updater. Then again, it doesn’t hurt to reboot, either, so it’s up to you.
Second, rebooting is meant to be a friendly process, allowing time for programs to exit, files to be saved, temporary files to be removed, filesystem journals updated, and so on. Whenever possible, reboot using the intended interfaces, whether in a GUI or a terminal. If you force your computer to shut down or reboot, you risk losing unsaved and even recently-saved data, and even corrupting important system information; you should only ever force your computer off when there’s no other option .
Click the button
The first way to reboot or shut down Linux is the most common one, and the most intuitive for most desktop users regardless of their OS: It’s the power button in the GUI. Since powering down and rebooting are common tasks on a workstation, you can usually find the power button (typically with reboot and shut down options) in a few different places. On the GNOME desktop, it’s in the system tray:
It’s also in the GNOME Activities menu:
On the KDE desktop, the power buttons can be found in the Applications menu:
You can also access the KDE power controls by right-clicking on the desktop and selecting the Leave option, which opens the window you see here:
Other desktops provide variations on these themes, but the general idea is the same: use your mouse to locate the power button, and then click it. You may have to select between rebooting and powering down, but in the end, the result is nearly identical: Processes are stopped, nicely, so that data is saved and temporary files are removed, then data is synchronized to drives, and then the system is powered down.
Push the physical button
Most computers have a physical power button. If you press that button, your Linux desktop may display a power menu with options to shut down or reboot. This feature is provided by the Advanced Configuration and Power Interface (ACPI) subsystem, which communicates with your motherboard’s firmware to control your computer’s state.
ACPI is important but it’s limited in scope, so there’s not much to configure from the user’s perspective. Usually, ACPI options are generically called Power and are set to a sane default. If you want to change this setup, you can do so in your system settings.
On GNOME, open the system tray menu and select Activities, and then Settings. Next, select the Power category in the left column, which opens the following menu:
In the Suspend & Power Button section, select what you want the physical power button to do.
The process is similar across desktops. For instance, on KDE, the Power Management panel in System Settings contains an option for Button Event Handling.
After you configure how the button event is handled, pressing your computer’s physical power button follows whatever option you chose. Depending on your computer vendor (or parts vendors, if you build your own), a button press might be a light tap, or it may require a slightly longer push, so you might have to do some tests before you get the hang of it.
Beware of an over-long press, though, since it may shut your computer down without warning.
Run the systemctl command
If you operate more in a terminal than in a GUI desktop, you might prefer to reboot with a command. Broadly speaking, rebooting and powering down are processes of the init system—the sequence of programs that bring a computer up or down after a power signal (either on or off, respectively) is received.
On most modern Linux distributions, systemd is the init system, so both rebooting and powering down can be performed through the systemd user interface, systemctl. The systemctl command accepts, among many other options, halt (halts disk activity but does not cut power) reboot (halts disk activity and sends a reset signal to the motherboard) and poweroff (halts disk acitivity, and then cut power). These commands are mostly equivalent to starting the target file of the same name.
For instance, to trigger a reboot:
Run the shutdown command
Traditional UNIX, before the days of systemd (and for some Linux distributions, like Slackware, that’s now), there were commands specific to stopping a system. The shutdown command, for instance, can power down your machine, but it has several options to control exactly what that means.
This command requires a time argument, in minutes, so that shutdown knows when to execute. To reboot immediately, append the -r flag:
To power down immediately:
Or you can use the poweroff command:
To reboot after 10 minutes:
The shutdown command is a safe way to power off or reboot your computer, allowing disks to sync and processes to end. This command prevents new logins within the final 5 minutes of shutdown commencing, which is particularly useful on multi-user systems.
On many systems today, the shutdown command is actually just a call to systemctl with the appropriate reboot or power off option.
Run the reboot command
The reboot command, on its own, is basically a shortcut to shutdown -r now. From a terminal, this is the easiest and quickest reboot command:
If your system is being blocked from shutting down (perhaps due to a runaway process), you can use the —force flag to make the system shut down anyway. However, this option skips the actual shutting down process, which can be abrupt for running processes, so it should only be used when the shutdown command is blocking you from powering down.
On many systems, reboot is actually a call to systemctl with the appropriate reboot or power off option.
On Linux distributions without systemd, there are up to 7 runlevels your computer understands. Different distributions can assign each mode uniquely, but generally, 0 initiates a halt state, and 6 initiates a reboot (the numbers in between denote states such as single-user mode, multi-user mode, a GUI prompt, and a text prompt).
These modes are defined in /etc/inittab on systems without systemd. On distributions using systemd as the init system, the /etc/inittab file is either missing, or it’s just a placeholder.
The telinit command is the front-end to your init system. If you’re using systemd, then this command is a link to systemctl with the appropriate options.
To power off your computer by sending it into runlevel 0:
To reboot using the same method:
How unsafe this command is for your data depends entirely on your init configuration. Most distributions try to protect you from pulling the plug (or the digital equivalent of that) by mapping runlevels to friendly commands.
You can see for yourself what happens at each runlevel by reading the init scripts found in /etc/rc.d or /etc/init.d, or by reading the systemd targets in /lib/systemd/system/.
Apply brute force
So far I’ve covered all the right ways to reboot or shut down your Linux computer. To be thorough, I include here additional methods of bringing down a Linux computer, but by no means are these methods recommended. They aren’t designed as a daily reboot or shut down command (reboot and shutdown exist for that), but they’re valid means to accomplish the task.
If you try these methods, try them in a virtual machine. Otherwise, use them only in emergencies.
A step lower than the init system is the /proc filesystem, which is a virtual representation of nearly everything happening on your computer. For instance, you can view your CPUs as though they were text files (with cat /proc/cpuinfo), view how much power is left in your laptop’s battery, or, after a fashion, reboot your system.
There’s a provision in the Linux kernel for system requests (Sysrq on most keyboards). You can communicate directly with this subsystem using key combinations, ideally regardless of what state your computer is in; it gets complex on some keyboards because the Sysrq key can be a special function key that requires a different key to access (such as Fn on many laptops).
An option less likely to fail is using echo to insert information into /proc, manually. First, make sure that the Sysrq system is enabled:
To reboot, you can use either Alt+Sysrq+B or type:
This method is not a reasonable way to reboot your machine on a regular basis, but it gets the job done in a pinch.
Sysctl
Kernel parameters can be managed during runtime with sysctl. There are lots of kernel parameters, and you can see them all with sysctl —all. Most probably don’t mean much to you until you know what to look for, and in this case, you’re looking for kernel.panic.
You can query kernel parameters using the -–value option:
If you get a 0 back, then the kernel you’re running has no special setting, at least by default, to reboot upon a kernel panic. That situation is fairly typical since rebooting immediately on a catastrophic system crash makes it difficult to diagnose the cause of the crash. Then again, systems that need to stay on no matter what might benefit from an automatic restart after a kernel failure, so it’s an option that does get switched on in some cases.
You can activate this feature as an experiment (if you’re following along, try this in a virtual machine rather than on your actual computer):
Now, should your computer experience a kernel panic, it is set to reboot instead of waiting patiently for you to diagnose the problem. You can test this by simulating a catastrophic crash with sysrq. First, make sure that Sysrq is enabled:
And then simulate a kernel panic:
Your computer reboots immediately.
Reboot responsibly
Knowing all of these options doesn’t mean that you should use them all. Give careful thought to what you’re trying to accomplish, and what the command you’ve selected will do. You don’t want to damage your system by being reckless. That’s what virtual machines are for. However, having so many options means that you’re ready for most situations.
Have I left out your favorite method of rebooting or powering down a system? List what I’ve missed in the comments!
How to Reboot Ubuntu through the Command Line
A reboot is a process of restarting a working computer with hardware (such as a power button) rather than software. After installing a software package, installing operating system updates, recovering from an error, or re-initializing drivers or hardware devices, you may need to reboot. In this article, we will be rebooting the Ubuntu machine through the command line. There are multiple ways for rebooting the system, so will explore each of the methods.
Reboot Ubuntu through Terminal
There are 4 methods for rebooting Ubuntu through Terminal. Let’s look at all the methods one by one.
Method 1: Using the Reboot Command
The below command will immediately reboot your Ubuntu operating system.
This will reboot your Ubuntu System.
Method 2: Using the Shutdown Command
The shutdown command is used to shut down your system, but it can also be used to restart it if you provide the -r flag. Here’s how you’d use the command in this situation:
Additionally, the following command can be used to schedule a system reboot.
The following command, for example, will restart your machine after 20 minutes.
You can also program your machine to reboot at a specified time.
For example, the following command will reboot my system at 8:20 pm.
For cancelling the shutdown command you can use the following command.
Method 3: Using the init Command
‘/sbin/init’ is the first process that runs when the kernel is loaded in Linux. It means the process has a PID of 1. Initialization is referred to as init. In simple terms, init’s job is to create processes based on scripts written in the /etc/inittab file, which is a configuration file utilized by the initialization system. The init command control file is specified in /etc/inittab, which is the last stage in the kernel boot procedure.
The ‘init 6’ command brings the system to a halt and restarts it in the state specified in ‘/etc/inittab’.
Use the below command to reboot Linux Ubuntu into a multiuser mode.
Use the command: to reboot into a Single-User State (Runlevel S).
Method 4: Using the Systemd command
Systemd is a system and service manager for Linux operating systems. It operates as an init system that starts up and maintains userspace services when started as the first process on boot (as PID 1).
Because Ubuntu is based on systemd, you can reboot your system using a systemd-specific command.
Перезагрузка компьютера в Linux
Эта статья ориентирована на самых новичков в Linux ну и тех кого интересует как перезагрузить Linux из консоли. Для меня перезагрузить компьютер в терминале или с помощью графического интерфейса это элементарно, но это база, не все новички ее знают и надо об этом написать.
Сегодня мы рассмотрим такие вопросы, как команда перезагрузки Linux из консоли, перезагрузка удаленно, и непосредственно перезагрузка в графическом интерфейсе. Начнем, пожалуй, с обычной перезагрузки системы.
Перезагрузка Linux в графическом интерфейсе
Здесь, как говорится, что может быть проще. Рассмотрим сначала перезагрузку в Ubuntu Unity. Достаточно нажать на кнопку с шестеренкой в правом верхнем углу экрана, и выбрать пункт Выключение:
Затем в открывшимся окне кликнуть по пункту Перезагрузка:
В окружении рабочего стола Gnome, все очень похоже на Unity, а в KDE нужно открыть главное меню, перейти на вкладку выход, и выбрать пункт перезагрузить:
Затем подтвердить перезагрузку.
Перезагрузка Linux в терминале
А здесь уже простор намного шире, существует около десятка команд, которыми можно перезагрузить Linux. Одним нужны root привилегии, другим нет, одни выглядят просто и легко запоминаются, а другие длинные и сложные. Дальше мы рассмотрим их все.
Первая команда перезагрузки Linux, самая распространенная и самая простая:
Как видите, утилите нужны права суперпользователя. После нажатия Enter компьютер сразу уйдет в перезагрузку.
Утилита shutdown, которая используется для выключения тоже позволяет перезагрузить компьютер для этого нужно передать ей параметр -r. Плюс к тому же можно указать время перезагрузки. Сейчас — 0 или now, через одну минуту +1 через две — +2 и т д:
sudo shutdown -r +1
Перезагрузка Linux будет выполнена через минуту после ввода команды.
В системах инициализации совместимых с Init Scripts, существовали уровни загрузки системы — 0,1,2,3,4,5,6, уровень 0 — означал выключение, 6 перезагрузку, остальные режимы работы системы нас сейчас не интересуют. Переключаться между уровнями можно командой init. Только опять же нужны права суперпользователя. Таким образом:
Служба системных сообщений dbus тоже умеет перезагружать компьютер:
/usr/bin/dbus-send —system —print-reply —dest=»org.freedesktop.ConsoleKit» /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.Restart
Тут уже не нужны права суперпользователя. Это были обычные способы перезагрузки Linux, но есть еще один, нестандартный или даже два. Это магические SysRq клавиши. Ядро Linux отслеживает нажатие определенных сочетаний клавиш, и в ответ на них выполняет нужные действия. Сначала включаем поддержку sysrq:
echo 1 > /proc/sys/kernel/sysrq
Лучше это сделать заблаговременно, так как этот способ полезен когда система зависла и ни на что не реагирует:
Для активации SysRq сочетания зажмите Alt + SysRq и нажмите код клавиши. Для нормальной перезагрузки рекомендуется использовать следующую последовательность: R E I S U B, клавиши нажимать в той же последовательности с интервалом приблизительно секунду.
- R — возвращает управление клавиатурой если Х сервер был завершен некорректно;
- E — ядро посылает всем процессам, кроме init сигнал SIGTERM;
- I — отправляет всем процессам, кроме init сигнал SIGKILL;
- S — ядро проводит синхронизацию файловых систем, все данные из кэша переносятся на жесткий диск;
- U — перемонтирует все файловые системы в режим только чтение;
- B — немедленная перезагрузка, без синхронизации, и дополнительных приготовлений.
Перед перезагрузкой система ожидает завершения всех процессов, останавливает все сервисы, отключает и монтирует в режиме только чтения файловые системы. Это мы и делаем, нажимая последовательно эти сочетания клавиш. Но если вам нужно перезагрузить систему сейчас не дожидаясь отключения всех процессов, например, сервер, можно сразу отправить сигнал B. Вот так: Alt + SysRq + B.
SysRq можно задействовать и без сочетаний клавиш, записав нужный код операции в файл /proc/sysrq-trigger:
echo b > /proc/sysrq-trigger
Система будет перезагружена как есть, без остановки сервисов и подготовки файловых систем, поэтому не сохраненные данные могут быть потеряны, а файловая система повреждена.
Удаленная перезагрузка Linux
Если у вас есть доступ к серверу по ssh то можно очень просто удаленно перезагрузить linux с помощью одной из выше приведенных команд, например:
ssh root@remote-server.com /sbin/reboot
Только опять же для этой операции нужно иметь права root на удаленном сервере.
Выводы
Теперь вы знаете как выполняется перезагрузка linux, вы даже знаете что делать когда система зависла и как перезагрузить сервер по ssh. Если у вас остались вопросы, спрашивайте в комментариях!
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Перезагрузка Linux через консоль
Обладатели разных дистрибутивов Linux время от времени сталкиваются с необходимостью перезагрузки операционной системы, что требуется делать после внесения каких-либо изменений в параметры или при появлении неполадок. Обычно поставленная задача осуществляется через графический интерфейс, но этот вариант не всегда получается использовать эффективно. Именно поэтому многие прибегают к вводу терминальных команд, которые и отвечают за подачу сигнала на перезагрузку. Сегодня мы хотим рассказать вам обо всех доступных способах перезапуска Линукс через консоль на примере Ubuntu.
Перезагружаем Linux через консоль
Как вы уже знаете, сегодняшние инструкции будут основаны на Ubuntu, однако и обладателям других дистрибутивов они тоже окажутся полезными, поскольку различия практически никогда не наблюдаются. Если же вдруг вы увидите сообщение об ошибке при попытке ввода какой-то команды, в следующих строках отобразится информация о том, почему этот запрос не может быть выполнен. Используйте полученные сведения, чтобы найти альтернативу, например, в официальной документации. Мы же переходим к рассмотрению всех методов, а их существует достаточное количество.
Способ 1: Команда reboot
О команде reboot наверняка слышали даже самые начинающие пользователи операционных систем Linux. Вся ее суть как раз и заключается в отправке текущего сеанса на перезагрузку, а дополнительные аргументы при этом не указываются.
-
Откройте меню приложений и запустите оттуда «Терминал». Для этого вы можете задействовать и другой удобный вариант, например, стандартную горячую клавишу Ctrl + Alt + T.
Компьютер сразу же завершит свою работу, и через несколько секунд запустится новый сеанс в обычном режиме. Автоматически включится виртуальная консоль с графической оболочкой, даже если до этого вы использовали другой терминал.
Способ 2: Команда shutdown
Иногда юзеру требуется, чтобы ПК перезапустился через определенное количество времени, например, через несколько минут. Команда reboot не очень подходит для таких целей, поэтому мы предлагаем воспользоваться альтернативой в виде shutdown.
- Запустите «Терминал» и укажите sudo shutdown -r +1 , где +1 — время, через которое команда будет приведена в действие. В данном случае это одна минута. Укажите 0 или now, если хотите запустить интересующий процесс немедленно.
- Команда shutdown тоже зависит от суперпользователя, поэтому для ее активации понадобится ввести пароль.
Способ 3: Init Script
Некоторые дистрибутивы поддерживают Init Script, о чем более детально вы можете прочесть в их официальных документациях. Там же будет написано и об основных настройках, связанных с данными скриптами. Сейчас мы опустим все эти моменты, поскольку они не вписываются в рамки этого материала. Расскажем лишь то, что у init есть шесть параметров, где 0 — выключение компьютера, а 6 — перезагрузка сеанса. Именно последний параметр мы и будем применять сейчас. Для его активации в консоли придется ввести sudo init 6 . Как вы уже поняли из приставки sudo, это действие тоже осуществляется только через root.
Способ 4: Служба системных сообщений D-Bus
Как вы наверняка заметили, все три приведенных выше способа для активации требовали наличия пароля суперпользователя, однако не у всех юзеров есть возможность ввести его. Специально для таких целей мы и предлагаем воспользоваться службой системных сообщений D-Bus. Это стандартная утилита Linux, позволяющая программам взаимодействовать друг с другом, а длинная и непонятная команда, отправляющая систему на перезапуск, следующая: /usr/bin/dbus-send —system —print-reply —dest=»org.freedesktop.ConsoleKit» /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.Restart . После ее ввода и активации текущий сеанс сразу же будет завершен.
Способ 5: Горячие клавиши SysRq
Этот метод только косвенно связан с консолью, поскольку через нее производится настройка, а дальнейшая перезагрузка выполняется через горячие клавиши. Однако мы решили включить его в этот список из-за необычности и особенностей использования. Горячие клавиши SysRq пригодятся в тех ситуациях, когда графическая оболочка попросту не отвечает.
- Запустите «Терминал» и введите там echo 1 > /proc/sys/kernel/sysrq .
- Следом откройте файл конфигурации через удобный текстовый редактор, например, sudo nano /etc/sysctl.conf .
- Этот файл расположен в системном разделе, поэтому для открытия понадобятся права суперпользователя.
- Опуститесь вниз файла и вставьте туда строку kernel.sysrq = 1 .
- Сохраните настройки и закройте текстовый редактор.
- После этого потребуется зажать Alt + SysRq + Код клавиши. Об этом мы детальнее поговорим далее.
Корректный перезапуск осуществляется путем указания определенной последовательности кодов клавиш. Каждый из них имеет следующий вид:
Клавиша | Описание |
---|---|
R | Вернет управление клавиатурой, если работа той была непредвиденно завершена |
E | Пошлет всем процессам сигнал SIGTERM, что приведет к их завершению |
I | Делает то же самое, но только через сигнал SIGKILL. Требуется в тех случаях, если некоторые процессы не были завершены после SIGTERM |
S | Отвечает за синхронизацию файловых систем. Во время этой операции вся информация будет сохранена на жестком диске |
U | Отмонтирует ФС и смонтирует их заново в режиме только для чтения |
B | Запустит процесс перезагрузки компьютера, игнорируя все предупреждения |
Вам осталось только нажать каждую эту комбинацию в этой же очередности, чтобы перезагрузка прошла корректно.
Способ 6: Удаленная перезагрузка
Некоторые пользователи активно задействуют специальные инструменты по удаленному управлению рабочими столами. Часто в подобных решениях имеются соответствующие команды, позволяющие отправить необходимый компьютер на перезапуск. Например, обратите внимание на следующий параметр SSH: ssh root@remote-server.com /sbin/reboot . Именно по этому принципу происходит перезапуск выбранного удаленного ПК на этом сервере. Если вы используете другие средства управления, прочтите официальную документацию, чтобы получить нужные сведения.
Способ 7: Перезагрузка в Recovery Mode
В качестве последнего способа мы хотим рассказать, как осуществляется перезагрузка ПК в Recovery Mode, поскольку многие пользователи теряются в этом меню и просто выключают компьютер через кнопку, а потом заново его запускают. В случае, когда вы перешли в режим восстановления, можете запустить консоль и использовать любой из приведенных выше методов:
- В меню восстановления вас интересует пункт «Продолжить нормальную загрузку» или «Перейти в командный интерпретатор суперпользователя». В первом случае просто начнется старт ОС в обычном режиме, а второй пункт запустит консоль в root.
- Если вы запускаете терминал, то подтвердите эту операцию нажатием на клавишу Enter.
- Далее остается только ввести подходящую команду, например, reboot , чтобы отправить ПК на перезапуск.
Как видите, существует огромное количество методов, позволяющих быстро перезагрузить систему Linux через консоль. Осталось только понять, какой из этих вариантов следует использовать в определенной ситуации, чтобы соответствовать возникшим условиям, которые требуют перезапуска ОС.