In Linux, you can get the exit status of a process using various methods. However, if you want to get the exit status of an unrelated process (i.e., a process that you did not start), you will need to use system calls or utilities that can access process information. Here are a few methods to achieve this:
Method 1: Using /proc Filesystem
The /proc filesystem provides a way to access information about running processes. You can read the exit status of a process from the /proc/[pid]/status file.
Find the Process ID (PID):
Use ps, pgrep, or pidof to find the PID of the process.
sh
pgrep process_name
Read the Exit Status:
If the process has terminated, you can read the exit status from /proc/[pid]/status.
sh
cat /proc/[pid]/status | grep "Exit"
Note that this will only work if the process has terminated and the /proc/[pid]/status file still exists.
Method 2: Using wait System Call
If you have the PID of a process and you want to wait for it to terminate and get its exit status, you can use the wait system call in a C program.
c
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid = 1234; // Replace with the actual PID
int status;
if (waitpid(pid, &status, 0) == -1) {
perror("waitpid");
return 1;
}
if (WIFEXITED(status)) {
printf("Process exited with status %d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("Process was killed by signal %d\n", WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
printf("Process was stopped by signal %d\n", WSTOPSIG(status));
} else if (WIFCONTINUED(status)) {
printf("Process was continued\n");
}
return 0;
}
Method 3: Using ps and grep
You can use ps and grep to find the exit status of a process if it has terminated and the information is still available in the process table.
sh
ps -o stat= -p [pid]
This command will give you the process state, which includes the exit status if the process has terminated.
Method 4: Using kill with -0
You can use the kill command with the -0 option to check if a process is still running. This does not give you the exit status but can help you determine if the process has terminated.
sh
kill -0 [pid]
If the process is still running, the command will return success (exit status 0). If the process has terminated, the command will return failure (exit status 1).
Summary
/proc Filesystem: Read the exit status from /proc/[pid]/status.
wait System Call: Use in a C program to wait for the process to terminate and get the exit status.
ps and grep: Use to find the process state, which includes the exit status if the process has terminated.
kill -0: Check if the process is still running.
Choose the method that best fits your needs based on whether you need to check the exit status of a running or terminated process.