Terry Li
Terry Li

Reputation: 17268

How to check if a process or thread is alive or not given their IDs in C++?

Given a process or thread ID, how to write a C++ function to check if it is alive or not. I'd like to implement this on both Windows and Linux.

Upvotes: 0

Views: 3583

Answers (3)

Ed Heal
Ed Heal

Reputation: 60037

Telling if a process ID or thread ID is alive is two different questions.

Thread IDs are easier - They are a part of the process - and therefore the process should know that it has created them and can check if they are current.

Process IDs is a different question - A new process could be created after the previous onw has died with the same ID.

A good solution to this is if you have a family of co-operating processes. You can name them and use the name or shared memory instead. I recommend the latter.

Upvotes: 0

jweyrich
jweyrich

Reputation: 32260

If you're not willing to add an extra library dependency to your project, you could wrap system-specific code using pre-processor directives (e.g: #ifdef _WIN32).

Windows

The GetExitCode* functions return STILL_ACTIVE if they succeed and the process or thread still exists.

Linux

  • kill - Send the null signal (0) to check whether the pid is still valid.

Upvotes: 1

thiton
thiton

Reputation: 36059

You'll have to decide first if you are checking for a process or a thread. These two have very different semantics. For processes, try the unofficial Boost.Process. For threads, Boost.Threads.

Upvotes: 1

Related Questions