Linux Init – How to Shutdown or Restart with Custom Init

initlinuxrebootshutdown

After reading this answer, I thought it would be funny to roll my own init on Python, so I wrote this in /init-python.

#!/usr/bin/python3
import os
import subprocess
# Make / writable!
subprocess.call(['/bin/mount', '-o', 'rw,remount', '/'])
# Became IPython (Now we're at it, get a good shell!)
os.execv('/usr/bin/ipython3', ['init'])

Then added init=/init-python to the linux line in GRUB config. It works.

So I was wondering now… how to power off or reboot my system with my homemade init?

Best Answer

It can be done with reboot function (man 2 reboot).

import ctypes
libc = ctypes.cdll['libc.so.6']
RB_POWER_OFF = 0x4321fedc
RB_AUTOBOOT  = 0x01234567

def shutdown():
    libc.reboot(RB_POWER_OFF)

def reboot():
    libc.reboot(RB_AUTOBOOT)
Related Question