Skip to content

Instantly share code, notes, and snippets.

@s-shin
Created February 29, 2016 05:57
Show Gist options
  • Save s-shin/d8737e640301995c67cf to your computer and use it in GitHub Desktop.
Save s-shin/d8737e640301995c67cf to your computer and use it in GitHub Desktop.
IPC example by popen in ruby with timeout.
<?php
$num_iterates = $argv[1];
echo "iterates: $num_iterates\n";
foreach (range(1, $num_iterates) as $i) {
sleep($i);
echo "$i\n";
echo "ping\n";
}
# parent.rb <timeout> <iterate>
timeout_sec = ARGV[0].to_i || 3
num_iterates = ARGV[1].to_i || 5
puts "timeout: #{timeout_sec}"
puts "iterates: #{num_iterates}"
io = IO.popen("php child.php #{num_iterates}", 'r+')
pid = io.pid
puts "popened: #{pid}"
begin
is_loop_end = false
until is_loop_end
timeout(timeout_sec) do
if line = io.gets
case line.chomp
when "ping"
puts 'parent: ping received'
else
puts "child: #{line}"
end
else
is_loop_end = true
end
end
end
puts 'parent: loop end'
rescue Timeout::Error
puts 'parent: timeout!!! kill child'
Process.kill(:kill, pid)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment