What is the proper way to shutdown linux and then kill power? - linux

I am running Linux raspberrypi 3.6.11+ on a raspberrypi board with an external power supply. The power supply "off" switch is controlled via the GPIO's.
I'd like to do a "shutdown -h -P now", wait for the system to shutdown (halt), then kill the power by running a program (killpower) to toggle the appropriate gpio pin. My main goal is to ensure that the file system is in a state where it won't get corrupted when the power is removed.
I've tried to take advantage of the runlevel 1 script killproc that sends SIGTERM (and SIGKILL) to every running process. I wrote killpower to catch SIGTERM, wait 20 seconds, then send the gpio powerkill sequence. I also modified the killproc script to NOT SIGKILL my killpower pid even if it is still running after the SIGTERM timeout.
When this did not work, I discovered that after killproc runs, the /init.d/halt SCRIPT runs, which calls /sbin/halt. /sbin/halt also kills all processes with SIGKILL, so I expect my killpower proc got killed before the 20 seconds was up. Now, I don't see how this approach is going to work.
I also see that init can act on a SIGPWR signal (not recommended) but it can execute powerwait/powerfail. Is the system in a state to power off at this point? I can't seem to find out what these programs are supposed to implement.
I thought about installing another shutdown script in init.d but I'm confused about what run level it should "stop" at (level 1 or level 0).
Is it OK to kill power just before the /sbin/halt is executed as a result of the shutdown command? Am I correct that once /sbin/halt is executed, nothing else will ever run?

The way I power off a linux box when I am logged into it remotely is to simply use the 'poweroff' command. The system then shuts down properly and finally turns itself off--nothing more, nothing less, exactly what I want.

Related

How to cancel shutdown from the command line after issuing 'gnome-session-quit --power-off'

The operating system is Red Hat Enterprise Linux 8.2. When the battery gets to a certain chargining percentage in the system I work on, the following command is used to perform shutdown:
gnome-session-quit --power-off
It will display to the user a countdown of 60 seconds, which gives the user time to cancel the shutdown. In case the user didn't cancel yet, but plugged in the power cable, I would like to cancel the shutdown without the need for the user to press the 'cancel' button. Is there a way to cancel the shutdown from the command line?
I tried to kill the 'gnome-session-quit --power-off' process to see if it will cancel the shutdown, but it didn't.
Any suggestions?
What about use ps command to find the power-off process and abort it with a pkill or kill -9 or killall
====EDIT 03/26/21
An other possible solution of this issue is using poweroff command to shutdown so it can be cancelled by a shutdown -c which is a command which cancels a previously scheduled shutdown (even "now" is scheduled in this sense --- but whether the cancellation will prevent the reboot is a bit of a race in that case).

print to linux prompt from background process

I was playing on my virtual machine with some exploit learning tricks when i came across this script that was printing to 2 lines and then exit to prompt, and after 10 seconds it printed in my prompt like this :
[!] Wait for the "Done" message (even if you'll get the prompt back).
user#ubuntu:~/tests$ [+] Done! Now run ./exp
How is this possible ? It is clone involved or something like that ?
The program informs you that you should wait for the "Done" message even if you get the prompt back earlier.
This is because some other process is running, detached, in the background.
The process you started has finished, which is why you are getting the prompt back. But it spawned another (background) process, e.g. via fork() or some other mechanic. By the time you get your prompt back, that other process is still running, and you are told to wait for it to finish.
When it does, it prints "Done" to the standard output (stdout) it inherited from its parent -- which is (by default) the same terminal you used to start the initial process.
Not the smoothest design -- the main process could wait for the spawned process to finish before giving you that prompt back, since it is apparently important that other process finishes before you carry on. Perhaps the author didn't know how to do that. ;-)
The process, responsible for printing the messages are running in background (background process).
In general, running a process in background means detaching only the stdin, the stdout and stderr are still linked to the actual parent shell, so all the outputs are still visible on the terminal.

How to detect restart before terminating program on Linux

I want to detect that system is restarting before it terminates my program on Linux.
I tried using /var/run/utmp file to detect runlevel, put inotify on its changes but seems like system is closing this program before I get signal. I catch shutdown with it if I set runlevel with telinit command, but dont catch if I just restart with button on top-right corner in Ubuntu.
Any idea how can it be done?
Catch the SIGTERM signal and be quick with saving/doing whatever and then exit. You've got approximately 10 seconds before you'll get SIGKILL which you can't catch, and you'll be force terminated.
If the system isn't sending you a SIGTERM to allow proper shutdown, change your system to something proper, this is the standard way of doing it.
See man 7 signal and man 3 sigaction for signal handling.
(Note that I don't know of a standard way to check if a system is rebooting or not, I don't think such thing exists. But as mentioned above, a proper system will send you SIGTERM and let you do your cleanup/exit. Hard reboot excluded, because thats almost equivalent of pulling the power cord.)

Linux process in background - "Stopped" in jobs?

I'm currently running a process with the & sign.
$ example &
However, (please note i'm a newbie to Linux) I realised that pretty much a second after such command I'm getting a note that my process received a stopped signal. If I do
$ jobs
I'll get the list with my example process with a little note "Stopped". Is it really stopped and not working at all in the background? How does it exactly work? I'm getting mixed info from the Internet.
In Linux and other Unix systems, a job that is running in the background, but still has its stdin (or std::cin) associated with its controlling terminal (a.k.a. the window it was run in) will be sent a SIGTTIN signal, which by default causes the program to be completely stopped, pending the user bringing it to the foreground (fg %job or similar) to allow input to actually be given to the program. To avoid the program being paused in this way, you can either:
Make sure the programs stdin channel is no longer associated with the terminal, by either redirecting it to a file with appropriate contents for the program to input, or to /dev/null if it really doesn't need input - e.g. myprogram < /dev/null &.
Exit the terminal after starting the program, which will cause the association with the program's stdin to go away. But this will cause a SIGHUP to be delivered to the program (meaning the input/output channel experienced a "hangup") - this normally causes a program to be terminated, but this can be avoided by using nohup - e.g. nohup myprogram &.
If you are at all interested in capturing the output of the program, this is probably the best option, as it prevents both of the above signals (as well as a couple others), and saves the output for you to look at to determine if there are any issues with the programs execution:
nohup myprogram < /dev/null > ${HOME}/myprogram.log 2>&1 &
Yes it really is stopped and no longer working in the background. To bring it back to life type fg job_number
From what I can gather.
Background jobs are blocked from reading the user's terminal. When one tries to do so it will be suspended until the user brings it to the foreground and provides some input. "reading from the user's terminal" can mean either directly trying to read from the terminal or changing terminal settings.
Normally that is what you want, but sometimes programs read from the terminal and/or change terminal settings not because they need user input to continue but because they want to check if the user is trying to provide input.
http://curiousthing.org/sigttin-sigttou-deep-dive-linux has the gory technical details.
Just enter fg which will resolve the error when you then try to exit.

Linux i/o to running daemon / process

Is it possible to i/o to a running process?
I have multiple game servers running like this:
cd /path/to/game/server/binary
./binary arg1 arg2 ... argn &
Is it possible to write a message to a server if i know the process id?
Something like this would be handy:
echo "quit" > process1234
Where process1234 is the process (with sid 1234).
The game server is not a binary written by me, but it is a Call of Duty binary. So i can't change anything to the code.
Yes, you can start up the process with a pipe as its stdin and then write to the pipe. You can used a named or anonymous pipe.
Normally a parent process would be needed to do this, which would create an anonmyous pipe and supply that to the child process as its stdin - popen() does this, many libraries also implement it (see Perl's IPC::Open2 for example)
Another way would be to run it under a pseudo tty, which is what "screen" does. Screen itself may also have a mechanism for doing this.
Only if the process is listening for some message somewhere. For instance, your game server can be waiting for input on a file, over a network connection, or from standard input.
If your process is not actively listening for something, the only things you can really do is halt or kill it.
Now if your process is waiting on standard input, and you ran it like so:
$ myprocess &
Then (in linux) you should be able to try the following:
$ jobs
[1]+ Running myprocess &
$ fg 1
And at this point you are typing standard input into your process.
You can only do that if the process is explicitly designed for that.
But since you example is requesting the process quit, I'd recommend trying signals. First try to send the TERM (i.e. terminate) signal which is the default:
kill _pid_
If that doesn't work, you can try other signals such as QUIT:
kill -QUIT _pid_
If all else fails, you can use the KILL signal. This is guaranteed (*) to stop the process but the process will have no change to clean up:
kill -KILL _pid_
* - in the past, kill -KILL would not work if the process was hung when on a flaky network file server. Don't know if they ever fixed this.
I'm pretty sure this would work, since the server has a console on stdin:
echo "quit" > /proc/<server pid>/fd/0
You mention in a comment below that your process does not appear to read from the console on fd 0. But it must on some fd. ls -l /proc/<server pid/>/fd/ and look for one that's pointing at /dev/pts/ if the process is running in a gnome-terminal or xterm or something.
If you want to do a few simple operations on your server, use signals as mentioned elsewhere. Set up signal handlers in the server and have each signal perform a different action e.g.:
SIGINT: Reread config file
SIGHUP: quit
...
Highly hackish, don't do this if you have a saner alternative, but you can redirect a process's file descriptors on the fly if you have ptrace permissions.
$ echo quit > /tmp/quitfile
$ gdb binary 1234
(gdb) call dup2(open("/tmp/quitfile", 0), 0)
(gdb) continue
open("/tmp/quitfile", O_RDONLY) returns a file descriptor to /tmp/quitfile. dup2(..., STDIN_FILENO) replaces the existing standard input by the new file descriptor.
We inject this code into the application using gdb (but with numeric constants, as #define constants may not be available), and taadaah.
Simply run it under screen and don't background it. Then you can either connect to it with screen interactively and tell it to quit, or (with a bit of expect hackery) write a script that will connect to screen, send the quit message, and disconnect.

Resources