Search code examples
linuxc++11posixmutexsemaphore

Call piece of c++ code once in multiprocess environment


I am currently developing some piece of code which should execute once in multiprocess environment.

//foo.cpp --> Shared library linked by both process1 and process2
void foo() { std::cout << "foo : Makesure I call only once in multiprocess environment \n"; }

//process1.cpp
int main() { foo(); }

//process2.cpp
int main() { foo(); }

I need to call foo() function only once either by process1/process2 in C++ environment.

Only Alternative solution I can think off is to creating dummy_file inside foo at firsttime and print message, If file already exist should not print message.

any suggestion would be appreciated


Solution

  • Only Alternative solution I can think of is to creating dummy_file inside foo at firsttime and print message, If file already exist should not print message.

    Yes. This is a viable alternative. If you were on Windows I'd say it would be better to have a Registry entry instead so the file can't easily/accidentally be deleted, but I see you've tagged the question for linux.

    See this article on IPC for Linux for other solutions than using a file.