sub thread { ## spawn a process to run the first command my $pid = open SSH, '|-', 'ssh' or die $!; ## send the command print SSH 'the first command'; ## Sleep for a while sleep $timeout; ## if the process is still running if( kill 0, $pid ) { ## kill it kill 9, $pid; ## wait until it goes away sleep 1 while kill 0, $pid; ## Open a new ssh session $pid = open SSH, '|-', 'ssh' or die $!; } print SSH 'the second command'; close SSH; }