Suspend command in linux

Linux, suspend to RAM и ИБП

В случае периодических, но достаточно кратковременных, отключений электроэнергии и наличии недорого ИБП с 1-2 аккумуляторами на 7 А.ч, не всегда есть смысл выключать компьютер пока не дадут свет. Особенно если вам долго и сложно поднимать рабочее окружение. Ниже будут приведены замеры потребления мощности для конкретного десктопа и стратегия работы с ИБП при нестабильном электричестве.

Если очень грубо, Linux имеет два вида «спящего режима» — hibernate, когда состояние памяти сбрасывается на диск и при старте ОС оттуда же считывается, а второй suspend — питание на планки RAM подается, но останавливаются жесткие диски, вентиляторы, в т.ч. блока питания. Hibernate, на мой взгляд, малоактуален, с текущими объемами памяти, необходимостью дополнительной настройки, вероятностью высадить аккумулятор ИБП именно во время перехода в него. Из плюсов — если вы успеете перейти в hibernate, то разряд аккумулятора в ноль вам не страшен.

Но, следует помнить(спасибо ZlobniyShurik за дополнение) у suspend режима тоже есть недостатки:

1. Самое очевидное — иногда вместо кратковременных провалов напряжения таки случаются пропадания на несколько часов. В этом случае suspend станет смертельной ловушкой для данных. Перед тем как уйти в suspend сохраните все что можно.

2. Многие недорогие бесперебойники принципиально не рассчитаны на долгую работу от батарей даже с небольшой нагрузкой (перегрев повышающего преобразователя из-за плохо продуманного охлаждения и низкого кпд). Мало того, у части из них просто принудительно гасится электроника после N минут работы от батареи.

3. Ещё может подложить свинью Green mode (он, кстати, у части ИБП неотключаем). Ваш комп уходит в спячку, снижает потребление до 30-25-20 ватт, ИБП понимает, что в него ничего, кроме какой-то ненужной мелочи не включено и начинает экономить электроэнергию путём своего полного отключения

Тем не менее, Suspend позволяет достаточно быстро входить и выходить из него, без дополнительной настройки. Просто по команде «sudo systemctl suspend». А что с энергопотреблением?

Итак, конфигурация в режиме простоя кушающая электричество:

  • 2 монитора
  • процессор AMD FX-6300 + какая-то материнка
  • 4 планки RAM
  • 2 TB HDD 7200
  • DVD-ROM
  • внешний HDD по USB3
  • мышь, клавиатура, вебкамера

Все это потребляет 160 вт. С выключенными мониторами — 118 Вт. После нажатия «systemctl suspend» (компьютер переводит мониторы в режим standby) — 25 вт. Если выключить мониторы еще и физически — 23.5 Вт.

Таким образом перевод компьютера в режим suspend позволит вам увеличить время работы от ИБП в 5-6 раз. Что может быть достаточно, если вы примерно представляете частоту и длительность отключений света в своем регионе. Я не называю конкретных цифр по времени работы, потому что это сильно зависит от состояния аккумуляторов в ИБП, которые нужно менять(по моему опыту) не реже чем раз в 2 года, а откровенную китайщину — лучше раз в год.

И поскольку это линукс, то тут есть нюансы. При использовании docker, который любит менять таблицу маршрутизации, могут наблюдаться определенные проблемы с сетью. Чтобы этого не было, для ухода в suspend лучше использовать такой скрипт(который пускать из под root):

Источник

  • Suspend

Help on software suspend

This page gathers bits of information about getting software suspend to work in Debian. Because the core system components change rapidly among Debian versions, software suspend works differently on different versions of Debians. This page is divided according to Debian versions from new to old.

For more reading material, see also the links at the bottom of this page about hibernate and suspend.

Debian Jessie and newer (8 and newer)

With systemd, pm-utils and its hooks are not used any more, instead there’s systemd-suspend. To suspend use:

In Gnome

Another option, under Gnome shell, is to simply press ALT before clicking the shutdown button in the user menu.

Читайте также:  Add apps to kali linux

In KDE Plasma

KDE already has a suspend button in its normal shutdown menu, though it may instead be labelled as «Sleep» in Plasma 5.16 and newer. Cases where it might not appear are if powerdevil or upower aren’t installed. systemd is used if available, but it’s not required.

Note that if power management is suspended by an application, the system may not suspend automatically, even if configured otherwise in your Energy Saving settings. This is often done by media players, for instance, to keep the screen from dimming. The Battery and Brightness item in your system tray will let you know if power management is suspended, and what process is currently suspending it.

Disable suspend and hibernation

For systems which should never attempt any type of suspension, these targets can be disabled at the systemd level with the following:

To re-enable hibernate and suspend use the following command:

A modern alternative approach for disabling suspend and hibernation is to create /etc/systemd/sleep.conf.d/nosuspend.conf as

The above technique works on Debian 10 Buster and newer. See systemd-sleep.conf(5) for details.

If you just want to prevent suspending when the lid is closed you can set the following options in /etc/systemd/logind.conf:

Then run systemctl restart systemd-logind.service or reboot.

More information is available in the manpage: man logind.conf

Debian Wheezy (7)

A very notable change is that HAL is phased out. If you still have the hal package installed, you should remove it or it will interference with pm-utils during suspend.

If the suspend / resume works well on your system, you are lucky and no need to read anything on this page. Or else, the first step to debug is to enable debugging for pm-utils, who control the suspend and resume process.

Enabling Debugging for pm-utils

The log of suspend and resume processes are in file /var/log/pm-suspend.log. It contains moderately verbose information by default. More information can be enabled for debugging by inserting line export PM_DEBUG=true into the beginning of file /usr/lib/pm-utils/pm-functions.

Fixing corrupted video on resume

A very common issue found after the computer resumes is corrupted video (or black screen, or no LCD backlight). The first step is to check whether the system is still running, which can be simply done by pressing the Capslock button and check whether the Capslock LED is changing accordingly. If the system is still running, in most cases we need to add a video quirk for your video card.

Debian now has kernel mode setting (KMS) enabled by default for most Intel, nVidia and ATI video cards. But pm-utils’ video quirk does support KMS yet. So in most cases you should try disabling KMS first. The detail steps for your specific video card can be found on the KernelModesetting page.

After disabled KMS, if the video after resume still corrupts, you can try to suspend the system by using some video quirks. Read the manpage of the pm-suspend program for a very detailed explanation of all the quirks available, and try the combinations of them from command-line. If you successfully find one combination of quirks that works for your system, you can add them into /usr/lib/pm-utils/video-quirks to make them permanent. At the same time, please help to file a bug against the pm-utils package with a patch about your changes so it can benefit the mass.

A common issue found on systems upgrading from old versions of Debian is the enabling of quirk-s3-bios freezes the system during suspend. If your system freezes during suspend, check the pm-suspend.log carefully after enabled debugging and make sure quirk-s3-bios is not used.

Kernel testing facility

The kernel has a Suspend testing facility changelog.

Introduce sysfs attribute /sys/power/pm_test allowing one to test the suspend core code. Namely, writing one of the strings below to this file causes the suspend code to work in one of the test modes defined as follows: freezer test the freezing of processes devices test the freezing of processes and suspending of devices platform test the freezing of processes, suspending of devices and platform global control methods(*) processors test the freezing of processes, suspending of devices, platform global control methods and the disabling of nonboot CPUs core test the freezing of processes, suspending of devices, platform global control methods, the disabling of nonboot CPUs and suspending of platform/system devices

Читайте также:  Dell windows для d620

(*) These are ACPI global control methods on ACPI systems

Then, if a suspend is started by normal means, the suspend core will perform its normal operations up to the point indicated by given test level. Next, it will wait for 5 seconds and carry out the resume operations needed to transition the system back to the fully functional state. Writing «none» to /sys/power/pm_test turns the testing off.

When open for reading, /sys/power/pm_test contains a space-separated list of all available tests (including «none» that represents the normal functionality) in which the current test level is indicated by square brackets.

The actual message (for googlers) are suspend debug: Waiting for 5 seconds.

Источник

How To Suspend A Process And Resume It Later In Linux

Picture this scenario. You run a program. But, you don’t know how long it will take to finish. The process keeps running several minutes. You can’t wait that much longer, because some other important programs are waiting in the queue. Have you ever been in a situation like this? No worries! I just found a simple trick to suspend a process and resume it later in Linux.

What I am going to do is just pause the currently running process, do some other important tasks, and then resume the stopped process after all other processes are completed. This can be very useful when you have less RAM or Processor to do multi-task. You can pause the running processes at any time, and resume them later, without having to start them all over again. Now let us go ahead and learn to suspend or pause a running process and resume it later in Linux and Unix-like operating systems.

Suspend a process and resume it later in Linux

This is absolutely an easy! All you have to do is find the PID (Process ID) and using ps or ps aux command, and then pause it, finally resume it using kill command.

Let us see an example. I am going to download Ubuntu 18.04 netboot image using wget command:

Here, & symbol will move the running task (i.e. wget ) to the background without closing it.

Now, I want to pause this task and run other important tasks. To do so, first find the running processes using command:

Sample output:

As you see, the PID of wget command is 16143.

Let us stop this process now. To do so, run the following command from your Terminal:

Verify whether the process has been stopped or not using command:

Sample output:

See? The wget process has been stopped.

Go ahead and do other important tasks. Once all tasks are completed, resume the stopped process using command:

To verify it if the process is running, run ps command.

Suspend a process and resume it later in Linux

See? The process which we stopped earlier has been resumed!

Like I said already, this will be helpful if you can’t do multi-task in system that has low RAM or CPU speed.

First, find the pid of the running process using ps command. Then, pause it using kill -STOP

, and then hibernate your system. Resume your system and resume the stopped process using command kill -CONT

Does this work after restarting my system?

You might wonder, will this also work after a full system shutdown or reboot? NO. Because, the PIDs of the processes will automatically change after rebooting your system. They do not persist across reboot. In such cases, you can suspend or hibernate your entire system, and resume them when you are ready.

And, that’s all. You know now how to pause and resume a process in Linux and Unix-like operating systems. Hope this helps.

Источник

How To Run Scripts And Commands On Suspend And Resume on Linux

Feb 6, 2018
Comment

The best way to run scripts and commands on suspend and resume on Linux before suspending (or after resuming) is to use the systemd init system. This is due to the fact that the init system interacts directly with the kernel, and power systems. Learning to work with this tool will allow any user to gain a lot of control over their Linux operating system,

Читайте также:  Eclipse ide download windows

Please understand that messing with the init system on your PC can be dangerous if you do not know what you are doing. Be sure to follow the instructions in this tutorial as closely as possible, to avoid any possible mishaps.

Not every modern Linux distribution supports the systemd init system. Some use upstart or something else entirely. In this tutorial, we’ll focus on systemd as it is the most common initiation system. If you’re looking to accomplish this task on something that doesn’t run what we cover in this article, consider looking into your operating system’s manual for instructions.

Note: Debian users should replace all instances of usr/lib/systemd/system-sleep with /lib/systemd/system-sleep/

Running A Command Before Suspend

To run a script before suspend, place any bash script file in the /usr/lib/systemd/system-sleep/ directory. The scripts themselves can do anything, but there is a certain syntax that must be adhered to. Start by opening up a terminal window. Using sudo -s, gain a root shell.

Next, up the nano text editor inside the system-sleep directory:

Add the shebang to the start of the script. Adding this is critical, and without it, the interpreter will not be able to correctly read the code and commands.

The next part of the script is the “if”. This will tell the power control system that “if” the system is about to go down for suspend, something should happen. Paste the code below:

Change sh /path/to/script/to/run.sh in the script to whatever you’d like to run on your Linux PC (or server) right before the system goes down for suspend. Keep in mind that the line directly after “if” does not need to be sh /path/to/script/to/run.sh. You can also use this to execute various commands. As long as bash can recognize it as a command, it will run.

The last part of the “before suspend” script is to add the “else if” portion. This aspect of the script doesn’t need to be modified, as, in this example, we’re worried about doing something before the system goes down, and not when it wakes back up.

When everything has been added to the file, press Ctrl + O to save nano.

Running A Command After Resume

Executing a command after resume works much like running something before suspend. The only real difference is instead of adding a command after the “if” portion of the script, you’d make the most important part of the code occur after the “elif” line.

To make a post-resume script, first, add the shebang as the first line.

On the next line, add the “if” portion of the script.

With that bit of code pasted into the bash script, move down and paste the “else if” section.

Once again, it’s OK to write anything under the “elif” line. As long as it is a normal command operation systemd and bash will run it.

Running Commands At Startup And Resume

If you’d like to run two opposite commands; one before suspend, and one at resume, it is possible. It just means customizing the script and adding lines under both the ‘if” line, as well as the “elseif” line.

Like usual, start out by posting the shebang into the script for the interpreter.

Next, paste the if section of the code.

Under if, replace “# replace with command” with whatever command you’d like to run right before the system goes down. Then, move to the “elif” section, and do the same.

Save the file with Ctrl + O,

Updating Permissions And Using The Script

All of the necessary commands are inside of the script file, but before it can run, you’ll need to update the permissions. Open up a terminal, and gain root with: su or sudo -s. Then do:

From now on, whenever you suspend or resume, custom commands inside of the script should run.

Источник

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