pid_t cpid = fork();
pid_t pid = getpid(); // Get current process ID
pid_t ppid = getppid(); // Get parent process ID
fork()
return value:
0
: Child process> 0
: Parent process, returns child's PID-1
: Fork failedMacro | Description |
---|---|
WIFEXITED(status) |
Checks if the process exited normally |
WEXITSTATUS(status) |
Retrieves the exit status |
WIFSIGNALED(status) |
Checks if the process was killed by a signal |
WTERMSIG(status) |
Retrieves the signal number |
WIFSTOPPED(status) |
Checks if the process was stopped |
WSTOPSIG(status) |
Retrieves the stopping signal |
WIFCONTINUED(status) |
Checks if the process was resumed |
if (WIFEXITED(status)) {
printf("Child exited normally, status=%d\\n", WEXITSTATUS(status));
}
if (WIFSIGNALED(status)) {
printf("Child killed by signal %d\\n", WTERMSIG(status));
}
if (WIFSTOPPED(status)) {
printf("Child stopped by signal %d\\n", WSTOPSIG(status));
} else if (WIFCONTINUED(status)) {
printf("Child continued\\n");
}
pid_t wait(int *status);
status
.-1
on error (no child exists).Return Value | Meaning |
---|---|
> 0 |
PID of the terminated child process |
-1 |
No child processes or an error occurred |
Example
int status;
pid_t pid = wait(&status);
if (pid > 0) printf("Child %d terminated\\n", pid);
pid_t waitpid(pid_t pid, int *status, int options);
Return Value | Meaning |
---|---|
> 0 |
PID of the terminated child process |
0 |
Child process is still running (WNOHANG mode) |
-1 |
Error (no child process or invalid call) |