How can I delete a UNIX Domain Socket file when I exit my application?
If you have multiple exit points from your application and you don't want to modify each of them to call cleanup routine, then you may use "dirty" approach.
When socket is just created, register cleanup routine with atexit(3)
. Routine (which is simply a call to unlink(2)
) will be called when application is terminated normally. But it won't be called if application is terminated with signal. So, if you want to cleanup after receiving SIGINT and similar signals, you also need to setup signal handlers properly.
You can check if socket if active by looking at /proc/net/unix. Then delete, ether in a cron, or before you start/restart your application.
echo "active sockets in /path/"
cat /proc/net/unix | grep -Eo '/path/.*'
echo "all sockets in path including stale sockets"
ls -1F /path/ | egrep '=$' | sed 's/=$//'
echo "example command to remove stale sockets"
comm -1 -3 <(cat /proc/net/unix | grep -Eo '/path/.*' | sort) <(ls -1F /path/ | egrep '=$' | sed 's/=$//' | sort) | xargs -n1 echo rm
You're making this harder than it needs to be. Put the unlink()
right before the bind()
. That's how everybody else does it. (Example: BSD syslogd, one of the classic unix-domain-socket-based services)