🧠 Context: What is status?
-
statusis anintpassed by reference towait()/waitpid(). - When a child process terminates, the kernel writes information about how it terminated into
status. - You then use macros like
WIFSIGNALED(status)to interpret that information.
🔍 1. WIFSIGNALED(status)
"Was the child process terminated by an uncaught signal?"
- This macro checks if the child died because of a signal, not because it called
exit()or returned frommain(). -
Returns non-zero (true) if:
- The child process ended due to a signal, not normal exit.
- The signal was not caught or ignored, meaning it went unhandled.
💡 Example:
#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// Child process: cause segmentation fault
int *p = NULL;
*p = 1; // SIGSEGV
} else {
int status;
waitpid(pid, &status, 0);
if (WIFSIGNALED(status)) {
printf("Child was killed by signal %d\n", WTERMSIG(status));
if (WCOREDUMP(status))
printf("Core dump was generated\n");
}
}
}
🛑 2. WTERMSIG(status)
"Which signal caused the termination?"
- If
WIFSIGNALED(status)is true, you can useWTERMSIG(status)to get the signal number. -
For example:
-
SIGSEGV= 11 (Segmentation fault) -
SIGKILL= 9 -
SIGINT= 2 (CTRL+C)
-
These signal numbers are defined in
<signal.h>.
💾 3. WCOREDUMP(status)
"Did the process create a core dump?"
- Some systems generate a core dump file when a process crashes due to a signal.
-
WCOREDUMP(status)checks whether that happened. - It’s not part of the official POSIX (SUSv3) standard, but it’s available on many systems like Linux, BSD, etc.
🧩 How does this work under the hood?
Internally, the status integer returned by wait() contains bit fields that encode:
- Whether the process exited normally or by signal
- What signal or exit code
- Whether a core dump occurred
Macros like WIFSIGNALED just check specific bits in that integer.
🧪 Summary Table
| Macro | What it tells you | Only valid when |
|---|---|---|
WIFSIGNALED(s) |
Process was killed by an uncaught signal | Always |
WTERMSIG(s) |
The signal number that killed it | When WIFSIGNALED(s) true |
WCOREDUMP(s) |
If a core dump was produced | When WIFSIGNALED(s) true (and supported) |
Top comments (0)