Here are several ways to check if a process exists:
Method 1: Using kill() with signal 0
#include <signal.h>
#include <errno.h>
int process_exists(pid_t pid) {
if (kill(pid, 0) == 0) {
return 1; // Process exists
} else if (errno == ESRCH) {
return 0; // Process doesn't exist
} else {
return -1; // Permission denied or other error
}
}
Method 2: Check /proc filesystem
#include <stdio.h>
#include <unistd.h>
int process_exists(pid_t pid) {
char path[32];
snprintf(path, sizeof(path), "/proc/%d", pid);
return access(path, F_OK) == 0;
}
Method 3: Using waitpid() (for child processes)
#include <sys/wait.h>
int child_exists(pid_t child_pid) {
int status;
pid_t result = waitpid(child_pid, &status, WNOHANG);
if (result == 0) {
return 1; // Child still running
} else if (result == child_pid) {
return 0; // Child has exited
} else {
return -1; // Error or not a child
}
}
Method 4: Using pidfd (Linux 5.1+)
#include <sys/syscall.h>
#include <sys/poll.h>
int process_exists_pidfd(pid_t pid) {
int pidfd = syscall(SYS_pidfd_open, pid, 0);
if (pidfd == -1) {
return 0; // Process doesn't exist
}
// Check if process has exited
struct pollfd pfd = {.fd = pidfd, .events = POLLIN};
int result = poll(&pfd, 1, 0);
close(pidfd);
if (result > 0 && (pfd.revents & POLLIN)) {
return 0; // Process has exited
} else {
return 1; // Process still alive
}
}
Method 5: Reading /proc/[pid]/stat
#include <stdio.h>
int process_exists_stat(pid_t pid) {
char path[32];
snprintf(path, sizeof(path), "/proc/%d/stat", pid);
FILE *file = fopen(path, "r");
if (file == NULL) {
return 0; // Process doesn't exist
}
fclose(file);
return 1; // Process exists
}
Shell/Command Line Methods:
# Method 1: Using ps
ps -p $PID > /dev/null 2>&1 && echo "exists" || echo "doesn't exist"
# Method 2: Using kill
kill -0 $PID 2>/dev/null && echo "exists" || echo "doesn't exist"
# Method 3: Check /proc
[ -d "/proc/$PID" ] && echo "exists" || echo "doesn't exist"
Comparison:
kill() with signal 0: Most portable, works on all Unix-like systems
/proc filesystem: Linux-specific, simple but requires filesystem access
waitpid(): Only works for child processes, but provides exit status
pidfd: Modern Linux feature, race-condition free but newer kernel requirement
/proc/[pid]/stat: More detailed but Linux-specific
For general use, kill(pid, 0) is the most portable and commonly used method.