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.

Note<br />

# Perché no? (Facile)<br />

# 2) Spiegate come agisce la funzione "eseguehanoi".<br />

# (Difficile)<br />

1. Il comando return è un builtin <strong>Bash</strong>.<br />

Capitolo 23. Funzioni<br />

2. Herbert Mayer definisce la ricorsività come “. . . esprimere un algoritmo usando una versione<br />

semplificata <strong>di</strong> quello stesso algoritmo. . .” Una funzione ricorsiva è quella che richiama sé stessa.<br />

3. Troppi livelli <strong>di</strong> ricorsività possono mandare in crash lo script con un messaggio <strong>di</strong> segmentation<br />

fault.<br />

#!/bin/bash<br />

# Attenzione: è probabile che l’esecuzione <strong>di</strong> questo script blocchi il sistema!<br />

# Se siete fortunati, verrete avvertiti da un segmentation fault prima che<br />

#+ tutta la memoria <strong>di</strong>sponibile venga occupata.<br />

funzione_ricorsiva ()<br />

{<br />

echo "$1" # Fa fare qualcosa alla funzione, accelerando il segfault.<br />

(( $1 < $2 )) && funzione_ricorsiva $(( $1 + 1 )) $2;<br />

# Finché il primo parametro è inferiore al secondo,<br />

#+ il primo viene incrementato ed il tutto si ripete.<br />

}<br />

funzione_ricorsiva 1 50000 # Ricorsività <strong>di</strong> 50,000 livelli!<br />

# Molto probabilmente segmentation fault (in base alla <strong>di</strong>mensione dello stack,<br />

#+ impostato con ulimit -m).<br />

# Una ricorsività così elevata potrebbe causare un segmentation fault<br />

#+ anche in un programma in C, a seguito dell’uso <strong>di</strong> tutta la memoria<br />

#+ allocata nello stack.<br />

echo "Probabilmente questo messaggio non verrà visualizzato."<br />

exit 0 # Questo script non terminarà normalmente.<br />

# Grazie, Stéphane Chazelas.<br />

464

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

Saved successfully!

Ooh no, something went wrong!