-1

Title says it all, I need to only allow one instance of my C program to be run. How can I accomplish this?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 4
    Possible duplicate of [How to create a single instance application in C or C++](https://stackoverflow.com/questions/5339200/how-to-create-a-single-instance-application-in-c-or-c) – zerkms Dec 17 '18 at 00:19
  • Note that the proposed duplicate does not include a solution based on shared memory as proposed in the [answer](https://stackoverflow.com/a/53807673/15168) given here. – Jonathan Leffler Dec 17 '18 at 03:50
  • Also, the proposed duplicate wants "a single instance" while this question wants to restrict the number of instances, e.g. only 3 instances running. – edin-m Dec 19 '18 at 14:40
  • @edin-m — your question explicitly says “one instance”. – Jonathan Leffler Dec 19 '18 at 15:49

1 Answers1

1

You can use shared memory for this purpose. Shared memory is an OS-level mechanism.

  1. Start instance #1 of your app
    • The app checks the shared memory if there is a value stored
    • If not, the app stores some value into the shared memory.
  2. Start instance #2 of your app
    • The app checks the shared memory if there is a value stored
    • The app sees there's already a shared memory value with a value and kills itself

You can use the shared memory to store the specific number of instances your app is allowed to run.

edin-m
  • 3,021
  • 3
  • 17
  • 27
  • A large number of fiddly details that have been quietly brushed under the carpet. One problem is unexpected crashes of the application — those leave the program unusable because the shared memory says there's a copy running but there isn't. (You need more data than just a number.) Another is that other processes can attach to the shared memory and alter the value stored at whim, defeating the purpose of the mechanism. You have to make the shared memory generally accessible if anyone is able to use the program, but that opens it up to abuse, too. I suspect there may be other issues lurking. – Jonathan Leffler Dec 17 '18 at 03:46
  • It's interesting that the proposed duplicate has no solution using shared memory. I'm not sure that's because of the problems I outlined. – Jonathan Leffler Dec 17 '18 at 03:47
  • @JonathanLeffler Those are good points but they're not eliminatory. #1 Not if using QSharedMemory on Windows; or you can use crash handlers. #2 A risk you're willing to take + you can encrypt data in your shared memory. I'd like to see more issues with this mentioned. Also, one will consider cost/benefits. – edin-m Dec 19 '18 at 15:12