linux – Script to shut down the computer when closing a certain program

Question:

How do I create a script so that when the rdesktop window is closed the computer is turned off?

Answer:

André Cabral

Would it close a program or a window?

Considering any program:

Create a file with the name you want, the examples below refer to ubuntu:

touch desliga_automatico

Put permission to execute:

sudo chmod +x desliga_automatico

Enter the code below:

#!/bin/sh
PROGRAMA='rdesktop' #nome do programa que deseja monitorar

while [ TRUE ] 
do
    if ps ax | grep -v grep | grep $PROGRAMA > /dev/null
    then
        #echo "$PROGRAMA está rodando"
    else
        #echo "$PROGRAMA não está rodando"
        sudo reboot 
    fi
    # colocamos o sleep para o processador ter tempo para realizar outras tarefas
    # você pode colocar o tempo que achar melhor (em segundos)
    sleep 120
done

In case it is a window and not a program:

#!/bin/sh
PROGRAMA='rdesktop'

while [ TRUE ]
do

    if xlsclients | grep -v grep | grep $PROGRAMA > /dev/null
    then
        #echo "$PROGRAMA está rodando"
    else
        echo "$PROGRAMA não está rodando"
        sudo reboot
    fi
    # colocamos o sleep para o processador ter tempo para realizar outras tarefas
    # você pode colocar o tempo que achar melhor (em segundos)
    sleep 120
done

If this suits your need, you can put it in:

sudo mv desliga_automatico /etc/init.d/ 

for it to start every time the computer starts

Hope this helps.

Scroll to Top