开发者

Mutex definition and use in C

I am writing a program using C. I want to have a mutex which can help me to run a new instance o开发者_如何学编程f a program in case the first instance of my program lost or stopped working.

I don't know how to start ... Any help would be really great.


If you are using Windows, then make a named mutex with CreateMutex. The first instance to run creates the mutex if it does not yet exists and locks it. Additional instances will fail to get ownership of the mutex using WaitForSingleObject and should terminate.

On Unix-like systems, it is typically to write the first instance's PID to a lock file. Other instances would then check that file versus the currently running programs. This is a bit more involved and does not utilize mutexes.


It seems I misread your question a bit and the prose above addresses the opposite: ensuring that only one instance runs at a time. To restart your process if it hangs or fails is more complicated. I would suggest a program that launches your application and monitors its health externally. The launcher could then start new instances when it detects a problem. The exact process is highly dependent on your platform.


You create a small loop that starts your program. So it will restart the program if it crashes.

In linux you can do this in a simple bash script

$ while true; do ./path/my/prog; done

In C, I would guess you write:

while(1) {
    system("./path/my/prog");
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜