Command for linux restart

How to Reboot Linux System (6 Methods)

how to reboot linux system

Linux users often take pride in the fact that they don’t need to reboot their system often, unlike Windows. However, sometimes in order for the changes to take place after a major software update, you may need to reboot even a Linux system. In addition to applying changes after an update, rebooting a system is also a highly effective solution to solve various issues. When you reboot the system, all running programs are removed from the primary memory as the Linux system is shutdown, and the initial boot-up process is followed from the scratch. But, rebooting a Linux system is quite different as compared to its counterparts. In this article, we will share command line and GUI methods for how to reboot your Linux system.

Reboot Linux System

How to Reboot Linux System Using Command Line

Linux command line gives its users great flexibility and options to play with when they need to reboot their systems. The command line method is handy when you need to reboot a Linux server. We recommend you use these commands carefully, otherwise, unintentionally executed commands can lead to data loss or data corruption altogether. That said, let’s look at the Linux commands we can use to reboot our Linux systems.

Reboot Linux Using shutdown Command

Firstly, shutdown is the easiest and one of the most used commands to reboot the Linux system. The syntax to reboot a Linux PC using the shutdown command is:

With the parameter, you can schedule the time for the reboot process. For example, if you need to reboot the system at 10:20 AM, use the command:

schedule a reboot for linux using the shutdown command

One great feature of the shutdown command is that all users who are currently logged into the system will get a broadcast message from the root user, informing them about the scheduled restart. To use a custom message for the users when a reboot is scheduled, you need to use this syntax:

For example, if you want to let the users know about the scheduled system restart at 10:00 AM, use this command:

sudo shutdown -r 10:00 «System reboot scheduled at 10 am. Kindly save your work beforehand»

schedule a reboot for Linux using the shutdown command

All users will get notified of the reboot on their terminal wall with the above broadcast message.

Reboot Linux Using reboot Command

When you reboot the system normally, the system goes through the process of first shutting down, and then the normal boot process is followed. When the reboot command is executed, the system firmware takes care of turning the system back on again. While the reboot command does not have a ton of options, it is simple to work with. The syntax to use the reboot command is:

Читайте также:  Linux создание своего скрипта

Some of the options to use with the reboot command are:

Options Description
-f When this flag is used, the normal process of the shutdown is not followed. Instead, the power to the system is directly cut off and a hardware signal is sent to the kernel to finally boot back the system.
-w When this flag is used, only an entry is made in the “system wtmp logs” instead of actually rebooting.
—help This flag is used to view the help menu of the reboot command consisting of the options and the syntax to use the reboot command
Reboot System Forcefully

If, for some reason, your system is malfunctioning, and you need to forcibly reboot the system, use this command:

rebooting a Linux system forcefully

Reboot Linux With the halt Command

The halt command is generally used to enable the halt mode, where the normal process of the shutdown is followed, except the power stays on. But you can also use the halt command to reboot your Linux system. When you reboot your PC with the halt command, it reboots the system immediately by following the normal reboot process. The syntax to reboot the system using the halt command is:

reboot using the halt command

Reboot Linux Using systemctl Command

The systemctl command refers to a centralized system management tool that can be used to manage and check the status of various services. One great use of this command is that it can also be used to change the system state. For example, systemctl command can also be used to reboot your Linux system. Use this command if you want to reboot using the systemctl command:

reboot linux using the systemctl

A default broadcast message is sent to all active users when you execute this command, informing them about the reboot. To send a custom message to all users, use this syntax:

sudo systemctl —message=»» reboot

For example, if you need to alert the users about a reboot session, you can use this command:

sudo systemctl —message=»System update, will be back soon» reboot

reboot using the systemctl command with a broadcast message

All active users will see the following message in their Linux terminal:

System update, will be back soon

Reboot Linux Using init Command

The init process is the first process that starts after the system has finished booting. init command is used to alter the system run levels. In order for Linux and other Unix-like operating to have a smooth operating, they have some pre-defined states known as “run Levels”. In each run level, a specific set of services and daemons are activated for the OS that can be modified by the user. There are 6 different run levels accessible to the root user:

Runlevel Description
0 Shuts down the system via normal procedure.
1 set single user-mode
2 set multi-user mode without networking
3 set multi-user mode with networking
4 used by the user for their specific needs
5 used to set multi-user mode with networking and GUI
6 used to reboot the system

To reboot your Linux system with the init command, use the following syntax:

reboot using the init command

How to Reboot Linux Using the GUI Method

Using the GUI in Linux distros to reboot a Linux system is the easiest method and even beginners can use it easily. But this method has a major tradeoff – you can reboot the Linux system via the GUI only in the desktop installations. Here, we have covered how you can reboot Linux systems running Gnome, Mate, and KDE-based distros.

Читайте также:  Astra linux графический вход в систему

Reboot Gnome-Based Linux Systems

1. Click on the top right-hand corner of the desktop to see a drop-down menu, as shown below. Click on the “Power Off/ Logout” option from the menu.

selecting the Power Off menu in Gnome

2. Then, select the “Restart” option from the sub-menu.

Restart option in Power Off Drop down menu

3. This will open a new dialogue box asking whether to restart the system or not. Click on the Restart button. Your system will get rebooted. If you do not select any option within 60 seconds, the system will automatically get rebooted.

Rebooting in Gnome-based systems

Reboot KDE-Based Linux Systems

1. Open the Applications tray from the bottom left-hand corner or press the Super key on the keyboard. The super key is labeled as the “Windows Icon” on most keyboards.

2. Here, select the “Quit” option from the bottom of the applications tray.

selecting the quit option in KDE

3. A new dialogue box will open with 3 options – Suspend, Restart, and Shutdown. Select the “Restart” option to reboot your Linux system.

Rebooting System in KDE

Reboot MATE-Based Systems

1. Click on the system menu from the top bar on the desktop and select the “Shut Down” option from the drop-down menu.

Selecting Shutdown option in MATE

2. Alternatively, you can click on the “Menu” button at the bottom left corner to open the application tray. The super key is labeled as the “Windows Icon” on most keyboards. Click on the ⏻ icon at the bottom of the application menu.

Selecting Turn off option in application menu of MATE

3. A new dialogue box will open with 3 options – Suspend, Restart, and Shutdown. Click on the “Restart” option to reboot your Linux system.

Rebooting MATE based system

Reboot Your Linux System Easily

Rebooting any computer can solve several issues ranging from simple app malfunctions to bootloader problems. While the command line method to reboot a Linux system is the most popular as it gives the users more flexibility and options to work with, the GUI method is the easiest for new users. We hope that this detailed guide on how to reboot a Linux system will help you. Meanwhile, check out our list of 50+ essential Linux commands to help you get used to and work more efficiently in the command line. Do let us know in the comments if you face any issues.

Источник

Перезагрузка компьютера в Linux

Эта статья ориентирована на самых новичков в Linux ну и тех кого интересует как перезагрузить Linux из консоли. Для меня перезагрузить компьютер в терминале или с помощью графического интерфейса это элементарно, но это база, не все новички ее знают и надо об этом написать.

Сегодня мы рассмотрим такие вопросы, как команда перезагрузки Linux из консоли, перезагрузка удаленно, и непосредственно перезагрузка в графическом интерфейсе. Начнем, пожалуй, с обычной перезагрузки системы.

Перезагрузка Linux в графическом интерфейсе

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

reboot_ubuntu1

Затем в открывшимся окне кликнуть по пункту Перезагрузка:

reboot_ubuntu2

В окружении рабочего стола Gnome, все очень похоже на Unity, а в KDE нужно открыть главное меню, перейти на вкладку выход, и выбрать пункт перезагрузить:

Читайте также:  Sudo apt get build dep linux

reboot_kde

Затем подтвердить перезагрузку.

Перезагрузка Linux в терминале

А здесь уже простор намного шире, существует около десятка команд, которыми можно перезагрузить Linux. Одним нужны root привилегии, другим нет, одни выглядят просто и легко запоминаются, а другие длинные и сложные. Дальше мы рассмотрим их все.

Первая команда перезагрузки Linux, самая распространенная и самая простая:

Как видите, утилите нужны права суперпользователя. После нажатия Enter компьютер сразу уйдет в перезагрузку.

Утилита shutdown, которая используется для выключения тоже позволяет перезагрузить компьютер для этого нужно передать ей параметр -r. Плюс к тому же можно указать время перезагрузки. Сейчас — 0 или now, через одну минуту +1 через две — +2 и т д:

Перезагрузка 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:

Система будет перезагружена как есть, без остановки сервисов и подготовки файловых систем, поэтому не сохраненные данные могут быть потеряны, а файловая система повреждена.

Удаленная перезагрузка Linux

Если у вас есть доступ к серверу по ssh то можно очень просто удаленно перезагрузить linux с помощью одной из выше приведенных команд, например:

ssh root@remote-server.com /sbin/reboot

Только опять же для этой операции нужно иметь права root на удаленном сервере.

Выводы

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

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Оцените статью
Adblock
detector