note 25491 deleted from function.fopen by aidan

From: Date: Tue, 28 Sep 2004 12:16:40 +0000
Subject: note 25491 deleted from function.fopen by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-77507@lists.php.net to get a copy of this message
Note Submitter: ben at gelbnet dot com ---- I was writing a shell script to get input from a user, however, I needed my script to time out after a certain number of seconds if the user didn't enter enough data. The code below descibes the method I used. It's a little hairy but it does work. -Ben #!/home/ben/php/bin/php -q <? //GLOBALS $RETURN_CHAR = "\n"; $TIMEOUT = 5; //number of seconds to timeout on input $PID = getmypid(); $CHILD_PID = 0; //Make sure program execution doesn't time out set_time_limit(0); function set_timeout() { global $PID; global $CHILD_PID; global $TIMEOUT; $CHILD_PID = pcntl_fork(); if($CHILD_PID == 0) { sleep($TIMEOUT); posix_kill($PID, SIGTERM); exit; } } function clear_timeout() { global $CHILD_PID; posix_kill($CHILD_PID, SIGTERM); } // read_data() // gets a line of data from STDIN and returns it function read_data() { $in = fopen("php://stdin", "r"); set_timeout(); $in_string = fgets($in, 255); clear_timeout(); fclose($in); return $in_string; } // write_data($outstring) // writes data to STDOUT function write_data($outstring) { $out = fopen("php://stdout", "w"); fwrite($out, $outstring); fclose($out); } while(1) { write_data("say something->"); $input = read_data(); write_data($RETURN_CHAR.$input); } ?>

« previous php.notes (#77507) next »