问题
I have a server application that creates a UNIX Domain Socket in a specific path with a name and bind()
s to it.
I need to delete the socket only when I close/stop the application intentionally, from within the the application code; otherwise it needs to be open. How do I do this?
Thanks!
Edit: Consider that I start and run my application from inside a terminal.
回答1:
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)
回答2:
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.
回答3:
Just execute
unlink("Path/to/Socket");
before you exit your program.
回答4:
You can remove the socket file with a simple:
unlink(path);
Wherever you program exit your program, check if it exists, and remove it.
回答5:
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
来源:https://stackoverflow.com/questions/34873151/how-can-i-delete-a-unix-domain-socket-file-when-i-exit-my-application