Skip to main content

101.3 Runlevel, Shutdown e Reboot


O processo de inicialização do Linux é iniciado por um processo com PID 1, tradicionalmente conhecido como init. Ele é o primeiro processo em espaço de usuário e, a partir dele, todos os demais processos do sistema são derivados. Basicamente é o primeiro processo a ser executado no Linux.


Hoje em dia, diferentes implementações do init podem ser encontradas dependendo da distribuição e da versão do sistema:

  • SysV Init

    O método tradicional, baseado em scripts localizados em /etc/init.d/ e links simbólicos em diretórios como /etc/rcX.d/, onde X representa o runlevel. Ainda é encontrado em algumas distribuições, mas tem sido gradualmente substituído.

  • Upstart

    Desenvolvido inicialmente pela Canonical, foi uma tentativa de modernizar o processo de inicialização, oferecendo suporte a eventos e inicialização paralela. Era muito usado em versões antigas do Ubuntu, mas caiu em desuso e foi substituído pelo SystemD.

  • SystemD

    Atualmente o padrão na maioria das distribuições modernas (como Red Hat, Fedora, Debian, Ubuntu, entre outras). Vai além do papel do init, funcionando como um gerenciador completo de sistema e serviços. Ele introduz o conceito de unidades (units), como serviços, sockets, targets etc. todas gerenciadas via o comando systemctl.

    O SystemD mantém compatibilidade com scripts SysV, permitindo que serviços legados ainda funcionem em sistemas mais novos.

  • OpenRC

    Embora não faça parte dos tópicos cobrados no exame, queria mencionar o OpenRC, usado principalmente em distribuições como Alpine Linux e Gentoo. Ele é uma alternativa leve e eficiente, que mantém compatibilidade com o estilo SysV, mas com suporte a paralelismo e dependências entre serviços.



SysV init


O SystemV Init (ou simplesmente SysV) trabalha com o conceito de runlevels, ou níveis de execução. Cada runlevel define um conjunto de serviços, scripts e programas que devem ser iniciados (ou finalizados) durante a inicialização ou mudança de estado do sistema.


As configurações principais ficam no arquivo /etc/inittab, que define qual runlevel deve ser carregado por padrão, além de mapear ações associadas a eventos específicos. Os scripts de inicialização ficam em /etc/init.d/ (um script por serviço) e são organizados por runlevel nos diretórios /etc/rcX.d/, onde X representa o número do runlevel.


Dentro desses diretórios, os scripts com prefixo S (de Start) serão iniciados, e os com K (de Kill) serão finalizados quando aquele runlevel for ativado.


Códigos do Runlevels:

CódigosDescrição
0Desligamento
1, s, S ou SingleSingle User (Usado para manutenção), só permite 1 usuário
2MultiUser sem rede
3MultiUser com rede
4Reservado para uso personalizado pelo administrador
5MultiUser com rede e Interface gráfica (usado em desktops)
6Reinicialização

Você pode verificar o runlevel padrão consultando o /etc/inittab, e o comando runlevel exibe o runlevel atual e o anterior. Para mudar de runlevel, use init X ou telinit X (onde X é o número do runlevel desejado). Ambos comandos têm o mesmo efeito.


Sempre que você alterar o arquivo /etc/inittab, deve recarregar as configurações com telinit q (ou telinit Q). Essa ação força o daemon a reler o arquivo. Já telinit u (ou U) apenas reaplica o runlevel atual, sem reler o inittab.


Abaixo temos um exemplo típico de um arquivo /etc/inittab usado em sistemas com SysV Init:

# Default runlevel
id:3:initdefault:

# Configuration script executed during boot
si::sysinit:/etc/init.d/rcS

# Action taken on runlevel S (single user)
~:S:wait:/sbin/sulogin

## id:runlevels:action:process
# Configuration for each execution level
l0:0:wait:/etc/init.d/rc 0
l1:1:wait:/etc/init.d/rc 1
l2:2:wait:/etc/init.d/rc 2
l3:3:wait:/etc/init.d/rc 3
l4:4:wait:/etc/init.d/rc 4
l5:5:wait:/etc/init.d/rc 5
l6:6:wait:/etc/init.d/rc 6

# Action taken upon ctrl+alt+del keystroke
ca::ctrlaltdel:/sbin/shutdown -r now

# Enable consoles for runlevels 2 and 3
1:23:respawn:/sbin/getty tty1 VC linux
2:23:respawn:/sbin/getty tty2 VC linux
3:23:respawn:/sbin/getty tty3 VC linux
4:23:respawn:/sbin/getty tty4 VC linux

# For runlevel 3, also enable serial
# terminals ttyS0 and ttyS1 (modem) consoles
S0:3:respawn:/sbin/getty -L 9600 ttyS0 vt320
S1:3:respawn:/sbin/mgetty -x0 -D ttyS1

Neste arquivo acima, cada linha define como o init deve reagir a eventos ou estados do sistema. A estrutura geral é:

id:runlevels:action:process

  • id: identificador da entrada, com até quatro caracteres.
  • runlevels: define os runlevels nos quais a ação deve ocorrer. Valores válidos vão de 0 a 6, embora 0 e 6 devam ser usados com cautela (pois correspondem a desligar e reiniciar o sistema).
  • action: especifica o comportamento do init em relação ao processo definido.
  • process: caminho do comando ou script a ser executado.

As ações disponíveis mais comuns são:

AçãoDescrição
bootExecuta o processo apenas uma vez durante a inicialização. Ignora o campo runlevels.
bootwaitSemelhante ao boot, mas o init aguarda o processo finalizar antes de continuar.
sysinitExecuta durante a inicialização, antes de qualquer runlevel ser ativado.
waitExecuta no(s) runlevel(s) especificado(s) e o init aguarda sua conclusão.
onceExecuta o processo uma única vez ao entrar no runlevel especificado.
respawnReinicia o processo sempre que ele for finalizado — comum para terminais.
ctrlaltdelExecuta quando o sistema recebe SIGINT via Ctrl+Alt+Del.

Esse tipo de configuração ainda aparece em sistemas mais antigos ou minimalistas, mas entender sua lógica continua relevante para ambientes legados e para compreender a evolução do processo de inicialização no Linux.


Scripts de inicialização:

# Verificando os scripts:
ls -l /etc/init.d/
total 156
-rwxr-xr-x 1 root root 3740 Apr 1 2020 apparmor
-rwxr-xr-x 1 root root 2964 Dec 6 2019 apport
-rwxr-xr-x 1 root root 1071 Jul 24 2018 atd
-rwxr-xr-x 1 root root 1232 Mar 27 2020 console-setup.sh
-rwxr-xr-x 1 root root 3059 Feb 11 2020 cron
-rwxr-xr-x 1 root root 937 Feb 4 2020 cryptdisks
-rwxr-xr-x 1 root root 896 Feb 4 2020 cryptdisks-early
-rwxr-xr-x 1 root root 3152 Sep 30 2019 dbus
-rwxr-xr-x 1 root root 985 Feb 12 2021 grub-common
-rwxr-xr-x 1 root root 2363 Jul 17 2017 haveged
-rwxr-xr-x 1 root root 3809 Jul 28 2019 hwclock.sh
-rwxr-xr-x 1 root root 4698 Jun 23 2018 ifplugd
-rwxr-xr-x 1 root root 2638 Dec 13 2019 irqbalance
-rwxr-xr-x 1 root root 1503 May 11 2020 iscsid
-rwxr-xr-x 1 root root 1479 Nov 27 2019 keyboard-setup.sh
-rwxr-xr-x 1 root root 2044 Feb 19 2020 kmod
-rwxr-xr-x 1 root root 695 Jan 28 2020 lvm2
-rwxr-xr-x 1 root root 586 Jan 28 2020 lvm2-lvmpolld
-rwxr-xr-x 1 root root 2827 Jan 9 2020 multipath-tools
-rwxr-xr-x 1 root root 4445 Jan 29 2019 networking
-rwxr-xr-x 1 root root 2503 May 11 2020 open-iscsi
-rwxr-xr-x 1 root root 1846 Mar 9 2020 open-vm-tools
-rwxr-xr-x 1 root root 1366 Mar 23 2020 plymouth
-rwxr-xr-x 1 root root 752 Mar 23 2020 plymouth-log
-rwxr-xr-x 1 root root 924 Feb 13 2020 procps
-rwxr-xr-x 1 root root 3117 Jan 28 2021 qemu-guest-agent
-rwxr-xr-x 1 root root 4417 Oct 15 2019 rsync
-rwxr-xr-x 1 root root 2864 Mar 7 2019 rsyslog
-rwxr-xr-x 1 root root 1222 Apr 2 2017 screen-cleanup
-rwxr-xr-x 1 root root 3939 May 29 2020 ssh
-rwxr-xr-x 1 root root 1582 Dec 23 2019 sysstat
-rwxr-xr-x 1 root root 6872 Apr 22 2020 udev
-rwxr-xr-x 1 root root 2083 Jan 21 2020 ufw
-rwxr-xr-x 1 root root 1391 Apr 13 2020 unattended-upgrades
-rwxr-xr-x 1 root root 1306 Apr 2 2020 uuidd

# Vendo os scripts de inicialização do Runlevel 3:
$ ls -lh /etc/rc3.d/
total 0
lrwxrwxrwx 1 root root 14 Aug 13 2020 K01cups -> ../init.d/cups
lrwxrwxrwx 1 root root 27 Aug 13 2020 K01speech-dispatcher -> ../init.d/speech-dispatcher
lrwxrwxrwx 1 root root 15 Aug 13 2020 S01acpid -> ../init.d/acpid
lrwxrwxrwx 1 root root 17 Aug 13 2020 S01anacron -> ../init.d/anacron
lrwxrwxrwx 1 root root 22 Aug 13 2020 S01avahi-daemon -> ../init.d/avahi-daemon
lrwxrwxrwx 1 root root 24 Nov 13 17:45 S01binfmt-support -> ../init.d/binfmt-support
lrwxrwxrwx 1 root root 19 Aug 13 2020 S01bluetooth -> ../init.d/bluetooth
lrwxrwxrwx 1 root root 26 Aug 13 2020 S01console-setup.sh -> ../init.d/console-setup.sh
lrwxrwxrwx 1 root root 14 Aug 13 2020 S01cron -> ../init.d/cron
lrwxrwxrwx 1 root root 22 Aug 13 2020 S01cups-browsed -> ../init.d/cups-browsed
lrwxrwxrwx 1 root root 14 Aug 13 2020 S01dbus -> ../init.d/dbus
lrwxrwxrwx 1 root root 17 Mar 19 16:59 S01glances -> ../init.d/glances
lrwxrwxrwx 1 root root 21 Aug 13 2020 S01grub-common -> ../init.d/grub-common
lrwxrwxrwx 1 root root 17 Aug 13 2020 S01hddtemp -> ../init.d/hddtemp
lrwxrwxrwx 1 root root 20 Aug 13 2020 S01irqbalance -> ../init.d/irqbalance
lrwxrwxrwx 1 root root 20 Aug 13 2020 S01kerneloops -> ../init.d/kerneloops
lrwxrwxrwx 1 root root 17 Aug 13 2020 S01lightdm -> ../init.d/lightdm
lrwxrwxrwx 1 root root 23 Aug 13 2020 S01lvm2-lvmpolld -> ../init.d/lvm2-lvmpolld
lrwxrwxrwx 1 root root 20 Jan 12 19:13 S01mintsystem -> ../init.d/mintsystem
lrwxrwxrwx 1 root root 27 Feb 28 20:58 S01nfs-kernel-server -> ../init.d/nfs-kernel-server
lrwxrwxrwx 1 root root 17 Aug 13 2020 S01openvpn -> ../init.d/openvpn
lrwxrwxrwx 1 root root 18 Aug 13 2020 S01plymouth -> ../init.d/plymouth
lrwxrwxrwx 1 root root 37 Aug 13 2020 S01pulseaudio-enable-autospawn -> ../init.d/pulseaudio-enable-autospawn
lrwxrwxrwx 1 root root 15 Aug 13 2020 S01rsync -> ../init.d/rsync
lrwxrwxrwx 1 root root 17 Aug 13 2020 S01rsyslog -> ../init.d/rsyslog
lrwxrwxrwx 1 root root 15 Aug 13 2020 S01saned -> ../init.d/saned
lrwxrwxrwx 1 root root 23 Mar 19 09:29 S01smartmontools -> ../init.d/smartmontools
lrwxrwxrwx 1 root root 23 Mar 26 11:47 S01spice-vdagent -> ../init.d/spice-vdagent
lrwxrwxrwx 1 root root 13 Jan 22 19:02 S01ssh -> ../init.d/ssh
lrwxrwxrwx 1 root root 15 Aug 13 2020 S01uuidd -> ../init.d/uuidd
lrwxrwxrwx 1 root root 20 Mar 22 12:33 S01virtualbox -> ../init.d/virtualbox

# Verificando do Runlevel 1:
$ ls -lh /etc/rc1.d/
total 0
lrwxrwxrwx 1 root root 20 Aug 13 2020 K01alsa-utils -> ../init.d/alsa-utils
lrwxrwxrwx 1 root root 22 Aug 13 2020 K01avahi-daemon -> ../init.d/avahi-daemon
lrwxrwxrwx 1 root root 19 Aug 13 2020 K01bluetooth -> ../init.d/bluetooth
lrwxrwxrwx 1 root root 14 Aug 13 2020 K01cups -> ../init.d/cups
lrwxrwxrwx 1 root root 22 Aug 13 2020 K01cups-browsed -> ../init.d/cups-browsed
lrwxrwxrwx 1 root root 17 Mar 19 16:59 K01glances -> ../init.d/glances
lrwxrwxrwx 1 root root 17 Aug 13 2020 K01hddtemp -> ../init.d/hddtemp
lrwxrwxrwx 1 root root 20 Aug 13 2020 K01irqbalance -> ../init.d/irqbalance
lrwxrwxrwx 1 root root 20 Aug 13 2020 K01kerneloops -> ../init.d/kerneloops
lrwxrwxrwx 1 root root 17 Aug 13 2020 K01lightdm -> ../init.d/lightdm
lrwxrwxrwx 1 root root 23 Aug 13 2020 K01lvm2-lvmpolld -> ../init.d/lvm2-lvmpolld
lrwxrwxrwx 1 root root 20 Feb 28 20:58 K01nfs-common -> ../init.d/nfs-common
lrwxrwxrwx 1 root root 27 Feb 28 20:58 K01nfs-kernel-server -> ../init.d/nfs-kernel-server
lrwxrwxrwx 1 root root 17 Aug 13 2020 K01openvpn -> ../init.d/openvpn
lrwxrwxrwx 1 root root 37 Aug 13 2020 K01pulseaudio-enable-autospawn -> ../init.d/pulseaudio-enable-autospawn
lrwxrwxrwx 1 root root 17 Feb 28 20:58 K01rpcbind -> ../init.d/rpcbind
lrwxrwxrwx 1 root root 17 Aug 13 2020 K01rsyslog -> ../init.d/rsyslog
lrwxrwxrwx 1 root root 15 Aug 13 2020 K01saned -> ../init.d/saned
lrwxrwxrwx 1 root root 23 Mar 19 09:29 K01smartmontools -> ../init.d/smartmontools
lrwxrwxrwx 1 root root 27 Aug 13 2020 K01speech-dispatcher -> ../init.d/speech-dispatcher
lrwxrwxrwx 1 root root 23 Mar 26 11:47 K01spice-vdagent -> ../init.d/spice-vdagent
lrwxrwxrwx 1 root root 13 Aug 13 2020 K01ufw -> ../init.d/ufw
lrwxrwxrwx 1 root root 15 Aug 13 2020 K01uuidd -> ../init.d/uuidd
lrwxrwxrwx 1 root root 20 Mar 22 12:33 K01virtualbox -> ../init.d/virtualbox

# Runlevel 0 (desligar) e 6 (reiniciar) devem matar os processos para tal efeito:
$ ls -lh /etc/rc6.d/
total 0
lrwxrwxrwx 1 root root 20 Aug 13 2020 K01alsa-utils -> ../init.d/alsa-utils
lrwxrwxrwx 1 root root 22 Aug 13 2020 K01avahi-daemon -> ../init.d/avahi-daemon
lrwxrwxrwx 1 root root 19 Aug 13 2020 K01bluetooth -> ../init.d/bluetooth
lrwxrwxrwx 1 root root 20 Aug 13 2020 K01cryptdisks -> ../init.d/cryptdisks
lrwxrwxrwx 1 root root 26 Aug 13 2020 K01cryptdisks-early -> ../init.d/cryptdisks-early
lrwxrwxrwx 1 root root 22 Aug 13 2020 K01cups-browsed -> ../init.d/cups-browsed
lrwxrwxrwx 1 root root 17 Mar 19 16:59 K01glances -> ../init.d/glances
lrwxrwxrwx 1 root root 17 Aug 13 2020 K01hddtemp -> ../init.d/hddtemp
lrwxrwxrwx 1 root root 20 Aug 13 2020 K01irqbalance -> ../init.d/irqbalance
lrwxrwxrwx 1 root root 20 Aug 13 2020 K01kerneloops -> ../init.d/kerneloops
lrwxrwxrwx 1 root root 17 Aug 13 2020 K01lightdm -> ../init.d/lightdm
lrwxrwxrwx 1 root root 23 Aug 13 2020 K01lvm2-lvmpolld -> ../init.d/lvm2-lvmpolld
lrwxrwxrwx 1 root root 20 Aug 13 2020 K01networking -> ../init.d/networking
lrwxrwxrwx 1 root root 20 Feb 28 20:58 K01nfs-common -> ../init.d/nfs-common
lrwxrwxrwx 1 root root 27 Feb 28 20:58 K01nfs-kernel-server -> ../init.d/nfs-kernel-server
lrwxrwxrwx 1 root root 17 Aug 13 2020 K01openvpn -> ../init.d/openvpn
lrwxrwxrwx 1 root root 18 Aug 13 2020 K01plymouth -> ../init.d/plymouth
lrwxrwxrwx 1 root root 37 Aug 13 2020 K01pulseaudio-enable-autospawn -> ../init.d/pulseaudio-enable-autospawn
lrwxrwxrwx 1 root root 17 Feb 28 20:58 K01rpcbind -> ../init.d/rpcbind
lrwxrwxrwx 1 root root 17 Aug 13 2020 K01rsyslog -> ../init.d/rsyslog
lrwxrwxrwx 1 root root 15 Aug 13 2020 K01saned -> ../init.d/saned
lrwxrwxrwx 1 root root 23 Mar 19 09:29 K01smartmontools -> ../init.d/smartmontools
lrwxrwxrwx 1 root root 27 Aug 13 2020 K01speech-dispatcher -> ../init.d/speech-dispatcher
lrwxrwxrwx 1 root root 23 Mar 26 11:47 K01spice-vdagent -> ../init.d/spice-vdagent
lrwxrwxrwx 1 root root 14 Aug 13 2020 K01udev -> ../init.d/udev
lrwxrwxrwx 1 root root 15 Aug 13 2020 K01uuidd -> ../init.d/uuidd
lrwxrwxrwx 1 root root 20 Mar 22 12:33 K01virtualbox -> ../init.d/virtualbox

# Runlvel 0
$ ls -lh /etc/rc0.d/
total 0
lrwxrwxrwx 1 root root 20 Aug 13 2020 K01alsa-utils -> ../init.d/alsa-utils
lrwxrwxrwx 1 root root 22 Aug 13 2020 K01avahi-daemon -> ../init.d/avahi-daemon
lrwxrwxrwx 1 root root 19 Aug 13 2020 K01bluetooth -> ../init.d/bluetooth
lrwxrwxrwx 1 root root 20 Aug 13 2020 K01cryptdisks -> ../init.d/cryptdisks
lrwxrwxrwx 1 root root 26 Aug 13 2020 K01cryptdisks-early -> ../init.d/cryptdisks-early
lrwxrwxrwx 1 root root 22 Aug 13 2020 K01cups-browsed -> ../init.d/cups-browsed
lrwxrwxrwx 1 root root 17 Mar 19 16:59 K01glances -> ../init.d/glances
lrwxrwxrwx 1 root root 17 Aug 13 2020 K01hddtemp -> ../init.d/hddtemp
lrwxrwxrwx 1 root root 20 Aug 13 2020 K01irqbalance -> ../init.d/irqbalance
lrwxrwxrwx 1 root root 20 Aug 13 2020 K01kerneloops -> ../init.d/kerneloops
lrwxrwxrwx 1 root root 17 Aug 13 2020 K01lightdm -> ../init.d/lightdm
lrwxrwxrwx 1 root root 23 Aug 13 2020 K01lvm2-lvmpolld -> ../init.d/lvm2-lvmpolld
lrwxrwxrwx 1 root root 20 Aug 13 2020 K01networking -> ../init.d/networking
lrwxrwxrwx 1 root root 20 Feb 28 20:58 K01nfs-common -> ../init.d/nfs-common
lrwxrwxrwx 1 root root 27 Feb 28 20:58 K01nfs-kernel-server -> ../init.d/nfs-kernel-server
lrwxrwxrwx 1 root root 17 Aug 13 2020 K01openvpn -> ../init.d/openvpn
lrwxrwxrwx 1 root root 18 Aug 13 2020 K01plymouth -> ../init.d/plymouth
lrwxrwxrwx 1 root root 37 Aug 13 2020 K01pulseaudio-enable-autospawn -> ../init.d/pulseaudio-enable-autospawn
lrwxrwxrwx 1 root root 17 Feb 28 20:58 K01rpcbind -> ../init.d/rpcbind
lrwxrwxrwx 1 root root 17 Aug 13 2020 K01rsyslog -> ../init.d/rsyslog
lrwxrwxrwx 1 root root 15 Aug 13 2020 K01saned -> ../init.d/saned
lrwxrwxrwx 1 root root 23 Mar 19 09:29 K01smartmontools -> ../init.d/smartmontools
lrwxrwxrwx 1 root root 27 Aug 13 2020 K01speech-dispatcher -> ../init.d/speech-dispatcher
lrwxrwxrwx 1 root root 23 Mar 26 11:47 K01spice-vdagent -> ../init.d/spice-vdagent
lrwxrwxrwx 1 root root 14 Aug 13 2020 K01udev -> ../init.d/udev
lrwxrwxrwx 1 root root 15 Aug 13 2020 K01uuidd -> ../init.d/uuidd
lrwxrwxrwx 1 root root 20 Mar 22 12:33 K01virtualbox -> ../init.d/virtualbox

# Verificando o Runlevel atual:
$ runlevel
N 5
# O 'N' indica que o runlevel não mudou desde que o sistema foi iniciado.

Para ver os serviços podemos usar os comandos abaixo:

# Ver status de todos os serviços:
$ service --status-all

# Ver staus do ssh:
$ sudo service sshd status
openssh-daemon (pid 1392) is running...

# Reiniciar um serviço:
$ sudo service rsyslog restart
Shutting down system logger: [ OK ]
Starting system logger: [ OK ]

# Parar um serviço:
$ sudo service rsyslog stop
Shutting down system logger: [ OK ]

# Iniciar um serviço:
$ sudo service rsyslog start
Starting system logger: [ OK ]


CHKCONFIG


O comando chkconfig fornece uma interface de linha de comando prática para gerenciar os links simbólicos nos diretórios /etc/rc[0-6].d/, facilitando para o administrador a tarefa manual de lidar com esses arquivos diretamente. Ele era usado em sistemas baseados em SysV Init, especialmente em distribuições Red Hat e derivadas.


Vale lembrar que nem todos os scripts em /etc/init.d/ estão mapeados nos runlevels, ou seja, apenas aqueles adicionados ao sistema de inicialização aparecerão na saída do chkconfig.


Opções comuns:

--add           = Adiciona um script à inicialização (cria os links nos diretórios rc[0-6].d)
--del = Remove o script da inicialização (remove os links nos diretórios rc[0-6].d)
--list = Lista todos os scripts registrados no chkconfig e seus estados nos runlevels
--level <N> = Define manualmente em quais runlevels o serviço estará 'on' ou 'off'

Exemplos:

# Verificando os scripts do sistema que estão na inicialização:
$ chkconfig
NetworkManager 0:off 1:off 2:on 3:on 4:on 5:on 6:off
auditd 0:off 1:off 2:on 3:on 4:on 5:on 6:off
blk-availability 0:off 1:on 2:on 3:on 4:on 5:on 6:off
crond 0:off 1:off 2:on 3:on 4:on 5:on 6:off
dnsmasq 0:off 1:on 2:off 3:off 4:off 5:off 6:off
haveged 0:off 1:off 2:on 3:on 4:on 5:on 6:off
ip6tables 0:off 1:off 2:on 3:on 4:on 5:on 6:off
iptables 0:off 1:off 2:on 3:on 4:on 5:on 6:off
iscsi 0:off 1:off 2:off 3:on 4:on 5:on 6:off
iscsid 0:off 1:off 2:off 3:on 4:on 5:on 6:off
ktune 0:off 1:off 2:off 3:on 4:on 5:on 6:off
lvm2-monitor 0:off 1:on 2:on 3:on 4:on 5:on 6:off
mdmonitor 0:off 1:off 2:on 3:on 4:on 5:on 6:off
messagebus 0:off 1:off 2:on 3:on 4:on 5:on 6:off
multipathd 0:off 1:off 2:off 3:off 4:off 5:off 6:off
netconsole 0:off 1:off 2:off 3:off 4:off 5:off 6:off
netfs 0:off 1:off 2:off 3:off 4:off 5:off 6:off
network 0:off 1:off 2:on 3:on 4:on 5:on 6:off
postfix 0:off 1:off 2:on 3:on 4:on 5:on 6:off
pppoe-server 0:off 1:off 2:off 3:off 4:off 5:off 6:off
qemu-ga 0:off 1:off 2:on 3:on 4:on 5:on 6:off
rdisc 0:off 1:off 2:off 3:off 4:off 5:off 6:off
restorecond 0:off 1:off 2:off 3:off 4:off 5:off 6:off
rsyslog 0:off 1:off 2:on 3:on 4:on 5:on 6:off
saslauthd 0:off 1:off 2:off 3:off 4:off 5:off 6:off
sshd 0:off 1:off 2:on 3:on 4:on 5:on 6:off
sysstat 0:off 1:on 2:on 3:on 4:on 5:on 6:off
tuned 0:off 1:off 2:on 3:on 4:on 5:on 6:off
udev-post 0:off 1:on 2:on 3:on 4:on 5:on 6:off
wpa_supplicant 0:off 1:off 2:off 3:off 4:off 5:off 6:off

# Verificar se um script está mapeado para inicialização:
$ chkconfig --list lvm2-lvmetad
service lvm2-lvmetad supports chkconfig, but is not referenced in any runlevel (run 'chkconfig --add lvm2-lvmetad')

# Adicionar o script à inicialização:
$ sudo chkconfig --add lvm2-lvmetad

# Confirmar que foi adicionado:
$ chkconfig --list lvm2-lvmetad
lvm2-lvmetad 0:off 1:on 2:on 3:on 4:on 5:on 6:off

# Desabilitar o script no runlevel 1:
$ sudo chkconfig --level 1 lvm2-lvmetad off

# Verificar novamente:
$ chkconfig --list lvm2-lvmetad
lvm2-lvmetad 0:off 1:off 2:on 3:on 4:on 5:on 6:off

Para reabilitar o serviço em um runlevel específico, basta usar on no lugar de off.



UPDATE-RC.D


O comando update-rc.d tem a mesma finalidade do chkconfig, mas é utilizado em distribuições baseadas em Debian, como o próprio Debian e o Ubuntu (quando operando com SysV ou scripts de compatibilidade).


Ele é usado para adicionar, remover, habilitar ou desabilitar scripts de inicialização nos diretórios /etc/rc[0-6].d/.

# Iniciando um script no boot (Para o runlevel 5):
$ sudo update-rc.d cups enable 5

# Desabilitando este script do runlevel 5:
$ sudo update-rc.d cups disable 5

## Se omitir o id do runlevel, ele será habilitado ou desabilitado nos runlevels [1-5]

# Remova todos os links para um script:
$ sudo update-rc.d cups remove
# Apaga ele dos diretórios /etc/rc[1-5].d/

# Adicionando um script no mapeamento (Podemos usar ele de novo com o Enable e Disable):
$ sudo update-rc.d cups defaults
# Adiciona ele dos diretórios /etc/rc[1-5].d/


SystemD


O systemd é o gerenciador de sistema e serviços padrão nas distribuições Linux modernas. Ele substitui o SysV Init com várias melhorias significativas, como paralelização nativa, dependências explícitas entre serviços, gerenciamento por socket/DBus, timers, targets e muito mais. Ele é usado por padrão em sistemas baseados em Red Hat, Debian, Ubuntu, Arch e outras distribuições recentes.


Com o systemd, o conceito de runlevels deixa de existir como entidade principal. Em seu lugar, temos:

  • Units: elementos fundamentais que representam serviços, sockets, dispositivos, pontos de montagem etc.
  • Targets: grupos de units que definem um estado do sistema, o equivalente moderno aos antigos runlevels.

Tipos comuns de units:

  • service: representa um daemon, como sshd.service, nginx.service, etc.
  • socket: define sockets do sistema ou de rede, ativa a unit de serviço correspondente quando há conexão.
  • device: associado a dispositivos do kernel, geralmente definidos por regras do udev.
  • mount: define pontos de montagem, como no /etc/fstab.
  • automount: ponto de montagem ativado automaticamente sob demanda.
  • target: agrupa várias units, usado para configurar estados como multiusuário, gráfico, etc.
  • snapshot: representa um estado salvo temporário do systemd (nem todas as distros suportam).
  • timer: substituto dos cron jobs, ativa services em horários ou intervalos específicos.

Os arquivos das units ficam geralmente em /lib/systemd/system/, e seguem o formato nome.tipo, por exemplo:

  • httpd.service
  • initrd.target
  • apt-daily.timer
  • systemd-fsckd.socket

Abaixo podemos conferir os parâmetros usados no comandos systemctl:

OpçõesDescrição
start (unit.service)Inicia a unit.
stop (unit.service)Interrompe unit.
restart (unit.service)Reinicia unit.
status (unit.service)Mostra o estado de unit, incluindo se está ou não em execução. Se está ou não ativa no boot.
is-active (unit.service)Exibe active se unit estiver rodando, ou inactive se não estiver.
is-enabled (unit.service)Verifica se unit é iniciado com o sistema. A resposta é armazenada na variável $?. O valor 0 indica que unit inicia com o sistema e o valor 1 indica que não.
enable (unit.service)Habilita unit na inicialização, ou seja, unit será carregado durante a inicialização do sistema.
disable (unit.service)unit não será iniciada com o sistema.
isolate (unit.target)Muda de target (Igual a telinit NUMERO, muda o runlevel atual)
set-default (unit.target)Configura um novo runlevel (Target nesse caso) default
get-defaultExibe o target default.
list-unit-filesLista todas as unidades disponíveis e mostra se elas estão habilitadas para iniciar quando o sistema é inicializado
list-unitsMostra as unidades ativas ou as que estiveram ativas durante a sessão atual do sistema.
--type=(Unit)Faz um filtro pelo tipo de Unit.
suspendColoca o sistema no modo de baixo consumo de energia, mantendo os dados atuais na memória.
hibernateCopia todos os dados da memória no disco, para que o estado atual do sistema possa ser recuperado após o desligamento.
poweroffDesliga a máquina.
rebootReinicia a máquina.
list-jobsListe os trabalhos que estão em andamento.

Para criar uma compatibilidade, temos runlevels apontando para targets:

#### Listando os targets que fazem compatibilidade com os Runlevels:
$ ls -lh /lib/systemd/system/runle*
/lib/systemd/system/runlevel0.target -> poweroff.target
/lib/systemd/system/runlevel1.target -> rescue.target
/lib/systemd/system/runlevel2.target -> multi-user.target
/lib/systemd/system/runlevel3.target -> multi-user.target
/lib/systemd/system/runlevel4.target -> multi-user.target
/lib/systemd/system/runlevel5.target -> graphical.target
/lib/systemd/system/runlevel6.target -> reboot.target

Ou seja, o antigo runlevel 3 corresponde a multi-user.target, e runlevel 5 a graphical.target.


Vejamos alguns comandos na prática:

# Vendo o Target/Runlevel default:
$ ls -l /lib/systemd/system/default.target
/lib/systemd/system/default.target -> graphical.target

# Vendo o Target/Runlevel default através do systemctl:
$ systemctl get-default
graphical.target

#### Podemos configurar um novo target default (runlevel) com o comando:
$ sudo systemctl set-default multi-user.target
Created symlink /etc/systemd/system/default.target → /lib/systemd/system/multi-user.target.

# Consulte novamente:
$ systemctl get-default
multi-user.target

# Para mudar apenas de target (não muda o default)
$ systemctl isolate nome.target

# Se quiser conferir o RunLevel ativo, você pode usar:
$ who -r
run-level 1 2021-11-13 19:21 last=5

# Iniciar o target Default
$ systemctl default

# Listar unidades específicas (podemos ver o status de todos os serviços do sistema)
$ systemctl list-units --type=service

# Listar unidades específicas (podemos ver o status de todos os serviços do sistema)
systemctl list-units -t service --full

### Listando as Units
$ systemctl list-units

Segue a imagem do comando acima:

dlmfawperikngpoiwrgn


Um pouco mais de comandos no SystemD:

# Reiniciar a máquina
$ sudo systemctl reboot

# Desligar a máquina
$ sudo systemctl poweroff

# Verificar estatus do serviço
$ sudo systemctl status nome.service

# Reiniciar o serviço
$ sudo systemctl restart nome.service

# Parar um serviço
$ sudo systemctl stop nome.service

# Habilitar um serviço na inicialização
$ sudo systemctl enable nome.service

# Combinção de 'start' e 'enable':
$ sudo systemctl enable --now nome.service

# Para desabilitar da inicialização
$ sudo systemctl disable nome.service

# Para verificar se está habilitado na inicialização
$ sudo systemctl is-enabled sshd.service
enabled

# Verificando se o serviço do ssh esta ativo:
$ sudo systemctl is-active sshd.service
active


UPSTART


Gerenciador de inicialização substituto ao Init. Ainda usa os scripts em /etc/init.d/ por compatibilidade, os arquivos de configuração ficam em /etc/init/.


Os comandos principais são:

# Lista os trabalhos e instancias conhecidas, exibe o status de cada um numa saída padrão.
$ initctl list

# Exibir o status
$ initctl status SERVIÇO

# Iniciar o serviço
$ initctl start SERVIÇO

# Para o serviço
$ initctl stop SERVIÇO


Shutdown e Restart


Reinicia ou Desliga o computador, enviando mensagens de aviso para todos os usuários conectados no sistema, podemos também agendar o desligamento.

Opções:

-P      = Desliga o Linux e a máquina
-h = Desliga o Linux mas não a máquina (depende do hardware)
-r = Reinicia
-c = Cancela o desligamento

Por padrão ele notifica os usuários que será feito o desligamento. Primeiro ele envia um SIGTERM e depois um SIGKILL.


Programando os desligamentos:

#### Default desligar depois de 1 minuto ####

#### +N agenda para N minutos o desligamento.
# Agendar para daqui 3 minutos
$ date ; sudo shutdown +3
Tue Mar 30 18:00:12 UTC 2021
Shutdown scheduled for Tue 2021-03-30 18:03:12 UTC, use 'shutdown -c' to cancel.

# Escolher um horario para desligar:
$ sudo shutdown 17:24

# Escolher um horario para desligar com power off:
$ sudo shutdown -P 17:24

# Escolher um horario para reiniciar:
$ sudo shutdown -r 17:24

# Para desligar ou reiniciar agora, usar 'now' ou '+0':
$ sudo shutdown -P now
$ sudo shutdown -r now

$ sudo shutdown -P +0
$ sudo shutdown -r +0

# Informando uma mensagem para delisgar o sistema:
$ sudo shutdown +3 "O Sistema será desligado em 3 minutos" &

Outros comandos que fazem isso:

# Desligar
poweroff
halt
systemctl poweroff
systemctl halt

# Reiniciar
reboot
systemctl reboot


WALL


Usado para enviar uma mensagem para todos os usuários do sistema, ou para um grupo de usuários.

# enviar a mensagem
$ wall "vamos desligar o sistema"

Broadcast message from vagrant@debian10.localdomain (pts/0) (Tue Mar 30 18:16:3

vamos desligar o sistema


ACPID - Advanced Configuration and Power Interface


O daemon acpid é o principal gerenciador de energia do Linux e permite ajustes mais refinados das ações após eventos relacionados ao consumo de energia, como fechar a tampa do laptop, bateria fraca ou níveis de carga da bateria.

Pode não vir instalado em algumas distros.