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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

file<strong>di</strong>sp="/proc/bus/usb/devices"<br />

USB1="Spd=12"<br />

USB2="Spd=480"<br />

veloc_bus=$(grep Spd $file<strong>di</strong>sp | awk ’{print $9}’)<br />

if [ "$veloc_bus" = "$USB1" ]<br />

then<br />

echo "Trovata porta USB 1.1."<br />

# Coman<strong>di</strong> inerenti alla porta USB 1.1.<br />

fi<br />

Capitolo 27. /dev e /proc<br />

La <strong>di</strong>rectory /proc contiene delle sotto<strong>di</strong>rectory con strani nomi numerici. Ognuno <strong>di</strong> questi nomi<br />

traccia l’ID <strong>di</strong> processo <strong>di</strong> tutti i processi correntemente in esecuzione. All’interno <strong>di</strong> ognuna <strong>di</strong> queste<br />

sotto<strong>di</strong>rectory, vi è un certo numero <strong>di</strong> file contenenti utili informazioni sui processi corrispondenti. I file<br />

stat e status contengono statistiche continuamente aggiornate del processo, il file cmdline gli<br />

argomenti da riga <strong>di</strong> comando con i quali il processo è stato invocato e il file exe è un link simbolico al<br />

percorso completo del processo chiamante. Di tali file ve ne sono anche altri (pochi), ma quelli elencati<br />

sembrano essere i più interessanti dal punto <strong>di</strong> vista dello <strong>scripting</strong>.<br />

Esempio 27-2. Trovare il processo associato al PID<br />

#!/bin/bash<br />

# pid-identifier.sh: Fornisce il percorso completo del processo associato al<br />

#+ pid.<br />

ARGNUM=1 # Numero <strong>di</strong> argomenti attesi dallo script.<br />

E_ERR_ARG=65<br />

E_ERR_PID=66<br />

E_ERR_PROCESSO=67<br />

E_ERR_PERMESSO=68<br />

FILEPROC=exe<br />

if [ $# -ne $ARGNUM ]<br />

then<br />

echo "Utilizzo: ‘basename $0‘ numero PID" >&2 # Messaggio d’errore >stderr.<br />

exit $E_ERR_ARG<br />

fi<br />

pidnum=$( ps ax | grep $1 | awk ’{ print $1 }’ | grep $1 )<br />

# Controlla il pid nell’elenco <strong>di</strong> "ps", campo nr.1.<br />

# Quin<strong>di</strong> si accerta che sia il processo effettivo, non quello invocato dallo<br />

#+ script stesso.<br />

# L’ultimo "grep $1" scarta questa possibilità.<br />

#<br />

# Come ha evidenziato Teemu Huovila, funziona anche:<br />

# numpid=$( ps ax | awk ’{ print $1 }’ | grep $1 )<br />

if [ -z "$pidnum" ] # Se, anche dopo il filtraggio, il risultato è una<br />

507

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

Saved successfully!

Ooh no, something went wrong!