There is an example that ships with freepascal called daemon.pp, it gives you the basics.