Code Snippets
Jump to navigation
Jump to search
This page holds random code snippets that do cool things:
This snippet creates a subprocess with a bi-directional pipe between them for communication. It can be used for (for example) wrapping a ssh connection (if you call setsid ssh will use the command defined in SSH_ASKPASS to request the password), daemonizing a process (see also Daemonize) or many other things...
require 'socket'
# create a new stream socket pair in the unix domain input, output = Socket.pair(Socket::AF_UNIX, Socket::SOCK_STREAM, 0) if pid = fork # forktastic Process.detach(pid) # if we exit, make sure the child doesn't zombie input.puts 'ho' sleep 10 input.puts 'bye' puts output.gets else Process.setsid # make the forked process run in a new session puts output.gets puts output.gets sleep 5 input.puts 'farewell' end