慕先生4541263 的学生作业:
#include
#include
#include
#include
#include
int main() {
pid_t pid1, pid2;
int status;
pid1 = fork();
if (pid1 < 0)
{
perror("[ERROR] fork():");
exit(EXIT_FAILURE);
} else if (pid1 == 0)
{
printf("pid1 (PID: %d) start execution\n", getpid());
sleep(2);
printf("pid1 (PID: %d) end execution\n", getpid());
} else
{
pid2 = fork();
if (pid2 < 0)
{
perror("[ERROR] fork():");
exit(EXIT_FAILURE);
} else if (pid2 == 0)
{
printf("pid2(PID: %d) start execution\n", getpid());
sleep(5);
printf("pid2(PID: %d) end execution\n", getpid());
} else {
waitpid(pid1, &status, 0);
printf("the parent process(pid: %d) has detected that the child process(pid: %d) has exited\n", getpid(), pid1);
waitpid(pid2, &status, 0);
printf("the parent process(pid: %d) has detected that the child process(pid: %d) has exited\n", getpid(), pid2);
printf("parent process(PID: %d) end execution\n", getpid());
}
}
return 0;
}