开发者

Allow start only one copy of program in linux

I want only one copy of my program开发者_StackOverflow社区 in the system. How can I look for another copies in the system from C-code? I want something like that

# program &
[1] 12586
# program &
Program is already running

The best idea I have is making .lock-files. But I didn't find any guildlines about them.

Thank you.


One daemon I wrote opened a UNIX domain socket for regular client-daemon communication. Other instances then checked whether they could connect to that socket. If they could, another instance was currently running. Edit: As noted by @psmears, there's a race condition. The other instances should just try to create that same listening socket. That will fail if it is already in use.

Lock files work more often than that special case. You may create an (empty) file in a well known location and then use file locks, say with fcntl(2) and F_SETLK and F_GETLK to set a lock on that file or determine whether a lock is held. May not work over NFS. Locks are cleared when your process dies, so this should work, and is portable (at least to HP-UX). Some daemons like to dump their pid into that file if they determine that no other instance is currently running.


You can use named sempahores, which is a very standard approach to this problem. Your program calls semctl() to find if there are any active sempahores, then checks to see if you can run. If you find none, then you create the sempahore.

The OS handles the problem of processes being killed off with kill -9 and leaving sempahores. You need to read the man page for semctl and sem_open for your machines to see what that mechanism is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜