c fork wait for child
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid;
int status;
pid = fork();
if (pid == 0) {
// Child process
printf("This is the child process\n");
sleep(3);
printf("Child process exiting\n");
return 0;
} else if (pid > 0) {
// Parent process
printf("This is the parent process\n");
// Wait for the child process to finish
wait(&status);
printf("Child process finished\n");
} else {
// Fork failed
printf("Fork failed\n");
return 1;
}
return 0;
}
This program demonstrates how to use the fork()
and wait()
system calls in C to create a child process and wait for it to finish in the parent process. When the program is run, the parent process creates a child process using fork()
. The child process then executes its own code, while the parent process waits for the child process to finish using wait()
. Once the child process finishes, the parent process resumes execution and continues its own code.