简体   繁体   中英

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 of 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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM