wait() and waitpid() Functions 🎯Welcome to the exciting world of C Programming! Today, we'll delve into the intricacies of the wait() and waitpid() functions, essential tools in handling child processes. Let's get started! 🚀
In C programming, a child process is a new process created by a parent process. Child processes can run concurrently with the parent process, allowing for efficient multitasking.
The wait() and waitpid() functions are used by the parent process to wait for the child process to terminate and gather information about the child process.
The wait() function waits for the termination of any child process in the parent process's process group and returns the process ID of the terminated child. If no child process has terminated, wait() blocks the parent process until a child terminates.
Here's a simple example:
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t childPid = fork();
if (childPid < 0) {
perror("Fork failed");
return 1;
} else if (childPid > 0) {
// Parent process
int status;
wait(&status);
printf("Parent: Child %d terminated with status: %d\n", childPid, WEXITSTATUS(status));
} else {
// Child process
sleep(5);
_exit(0);
}
return 0;
}The waitpid() function provides more flexibility than wait(), allowing the parent process to wait for a specific child process. It takes three arguments:
pid_t pid: The ID of the child process to wait for.int options: Bitmask specifying options.struct wp_stat_t *status_ptr: A pointer to a structure that stores information about the child process.Here's an example using waitpid():
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t childPid1 = fork();
pid_t childPid2 = fork();
if (childPid1 < 0 || childPid2 < 0) {
perror("Fork failed");
return 1;
}
if (childPid1 > 0) {
// Wait for childPid1 to terminate
int status;
waitpid(childPid1, &status, 0);
printf("Parent: Child %d terminated with status: %d\n", childPid1, WEXITSTATUS(status));
}
if (childPid2 > 0) {
// Wait for childPid2 to terminate
int status;
waitpid(childPid2, &status, 0);
printf("Parent: Child %d terminated with status: %d\n", childPid2, WEXITSTATUS(status));
}
return 0;
}WEXITSTATUS() macro is used to extract the exit status of the child process from the status returned by wait() or waitpid().WIFEXITED() and WIFSIGNALED() macros can be used to check whether the child process terminated due to exit or signal.Which function is used to wait for a specific child process?
That's all for today! As you practice, you'll become more comfortable with wait() and waitpid(). Happy coding! 🌟