11.04.2013 Views

Guida avanzata di scripting Bash - Portale Posta DMI

Guida avanzata di scripting Bash - Portale Posta DMI

Guida avanzata di scripting Bash - Portale Posta DMI

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Capitolo 11. Coman<strong>di</strong> interni e builtin<br />

Quando un comando, o la stessa shell, svolge un certo compito, dà origine (spawn) ad un<br />

nuovo sottoprocesso. Questa azione si chiama forking. Il nuovo processo è il figlio, mentre<br />

il processo che l’ha generato è il genitore. Mentre il processo figlio sta svolgendo il proprio<br />

lavoro, il processo genitore resta ancora in esecuzione.<br />

Si noti che mentre un processo genitore ottiene l’ID <strong>di</strong> processo del processo figlio,<br />

riuscendo in questo modo a passargli degli argomenti, non è vero l’inverso. Ciò può creare<br />

dei problemi che sono subdoli e <strong>di</strong>fficili da in<strong>di</strong>viduare.<br />

Esempio 11-1. Uno script che genera istanze multiple <strong>di</strong> sé stesso<br />

#!/bin/bash<br />

# spawn.sh<br />

PID=$(pidof sh $0) # ID dei processi delle <strong>di</strong>verse istanze dello script.<br />

P_array=( $PID ) # Inseriti in un array (perché?).<br />

echo $PID # Visualizza gli ID dei processi genitore e figlio.<br />

let "instanze = ${#P_array[*]} - 1" # Conta gli elementi, meno 1.<br />

# Perché viene sottratto 1?<br />

echo "$instanze instanza(e) dello script in esecuzione."<br />

echo "[Premete Ctl-C per terminare.]"; echo<br />

sleep 1 # Attesa.<br />

sh $0 # Provaci ancora, Sam.<br />

exit 0 # Inutile: lo script non raggiungerà mai questo punto.<br />

# Perché?<br />

# Dopo aver terminato l’esecuzione con Ctl-C,<br />

#+ saranno proprio tutte "morte" le istanze generate dallo script?<br />

# In caso affermativo, perché?<br />

# Nota:<br />

# ----<br />

# Fate attenzione a non tenere in esecuzione lo script troppo a lungo.<br />

# Potrebbe, alla fine, esaurire troppe risorse <strong>di</strong> sistema.<br />

# Uno script che genera istanze multiple <strong>di</strong> sé stesso<br />

#+ rappresenta una tecnica <strong>di</strong> <strong>scripting</strong> consigliabile.<br />

# Siete d’accordo oppure no?<br />

In genere, un builtin <strong>Bash</strong> eseguito in uno script non genera un sottoprocesso. Al contrario,<br />

un filtro o un comando <strong>di</strong> sistema esterno, solitamente, avvia (fork) un sottoprocesso.<br />

Un builtin può avere un nome identico a quello <strong>di</strong> un comando <strong>di</strong> sistema. In questo caso <strong>Bash</strong> lo<br />

188

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!