Skip to content

Instantly share code, notes, and snippets.

@bmc
Created December 28, 2010 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bmc/757519 to your computer and use it in GitHub Desktop.
Save bmc/757519 to your computer and use it in GitHub Desktop.
Run block as another user, in subprocess
require 'etc'
def as_user(user, &block)
# Find the user in the password database.
u = (user.is_a? Integer) ? Etc.getpwuid(user) : Etc.getpwnam(user)
# Fork the child process. Process.fork will run a given block of code
# in the child process.
Process.fork do
# We're in the child. Set the process's user ID.
Process.uid = u.uid
# Invoke the caller's block of code.
block.call(user)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment