daemonize: Run a command as a Unix daemon


What is daemonize?

daemonize is a small utility that lets you run a command as a Unix daemon even if the command itself doesn’t daemonize. It’s handy for turning long-running tasks into background services without writing a full init/systemd unit.

Common pitfall: not understanding that the command itself must be able to detach from the terminal. daemonize handles the backgrounding, not the command’s own behavior.

Basic usage

The simplest way to run a command as a daemon is:

daemonize {{command}} {{command_arguments}}
  • Example: run a long script in the background
daemonize /usr/local/bin/backup.sh --full

Write a PID file

If you want to keep track of the daemon process, write its PID to a file:

daemonize -p {{path/to/pidfile}} {{command}} {{command_arguments}}
  • Example:
daemonize -p /var/run/backup.pid /usr/local/bin/backup.sh --full

Use a lock file to prevent duplicates

Use a lock file so only one instance can run at a time:

daemonize -l {{path/to/lockfile}} {{command}} {{command_arguments}}
  • Example:
daemonize -l /var/lock/backup.lock /usr/local/bin/backup.sh --full

Run as a specific user

If you need the daemon to run under a specific account, use sudo with -u:

sudo daemonize -u {{user}} {{command}} {{command_arguments}}
  • Example:
sudo daemonize -u backup /usr/local/bin/backup.sh --full

Practical tips and pitfalls

  • Ensure the command can run unattended. If it prints to stdout/stderr, redirect logs to a file within the command or via the shell.
  • PID and lock files should be stored in appropriate system locations (e.g., /var/run or /tmp) with correct permissions.
  • If you’re using a lockfile, make sure it’s released on exit. Check for stale locks if the daemon crashed.
  • Running as root (via sudo) should be avoided unless necessary. Prefer a dedicated user with minimal privileges.

Quick checklist

  • Command can run non-interactively
  • PID file path is writable
  • Lock file path is writable and unique per instance
  • Optional: run as a non-root user
  • Log output is captured or redirected

If you plan to manage the daemon with a supervisor like systemd later, you can still prototype with daemonize to verify behavior before writing the service unit.

See Also