Praveen's Blog

An Eternal Quest for Incremental Improvement

Testing if a process or thread is alive

If one wants to check if a given thread or a process is alive in the system, here is the way of doing it. This code snippet is guaranteed to work on Linux NPTL threads. What we need as an input to this function is the tid (thread id) given by the kernel. You can get the tid of a thread by issuing gettid() system call. In case of a process, gettid() is going to return the pid (process id) of the process.

isalive( pid_t tid ) {
  if ( 0 != kill( tid, 0 ) && ESRCH == errno ) {
    /* The thread or process is not alive */
    return false;
  return true;

It should be noted that just checking for the return value of kill() is not going to be sufficient as it is going to be -1 even if the thread or the process exists but the calling process has no permission to send signal to it (errno is set to EPERM).

People say that pthread_kill() could also used to achieve the same purpose. But I ran into issues when trying that approach. Also pthread_kill() approach can't be used on processes. The kill() approach is uniform to both processes and threads. But one overhead in this approach is knowing or finding the tid of the thread of interest. Note that the tid used in kill() is not the pthread_t type but it is pid_t type.