Code Snippets

From WTFwiki
Revision as of 14:13, 24 September 2007 by Andrew (talk | contribs)
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

This snippet connects to a UNIX socket on the machine. If the server isn't running; it spawns one in a subprocess and detaches it. This is useful for robustness.

 require 'socket'
PATH=File.join(ENV['HOME'], '.testsock')
begin sock = UNIXSocket.new(PATH) rescue Errno::ENOENT, Errno::ECONNREFUSED => e File.delete(PATH) if File.socket?(PATH) if pid = fork() Process.detach(pid) sleep 1 retry else server = UNIXServer.new(PATH) loop do sock = server.accept sock.puts("Echo: "+sock.gets) end end end
sock.puts("HI!") puts sock.gets