Getting a unique id from a unix-like system

前端 未结 15 2445
不知归路
不知归路 2020-11-27 18:22

I want to get from any Unix-like system (if this is possible) a unique id that will be persistent every time my application runs in the same machine. If it is possible, I wa

15条回答
  •  情话喂你
    2020-11-27 19:12

    You can use a lockfile in places like:

    • /var/run/yourapp.pid (if program run by root)
    • $HOME/.yourapp.pid (if run by user and local filesystem)
    • $HOME/.yourapp.$(hostname -f).pid (home on nfs)

    When your program is run, it shall do something like:

    lock = open(filename, O_CREAT | O_EXCL);
    dprintf(lock, "%u", getpid());
    

    If the open fails, check if the process is still running and if not: delete the file and try again.

提交回复
热议问题