#include <stdlib.h> #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> int main () { pid_t pid,wpid; int status,i; pid=fork(); if(pid==0) { printf("This is the child process, process number(pid)is:%d\n",getpid()); sleep(5); exit(6); } else { printf("This is the parent process, waiting for the child process鈥︹€n"); wpid=wait(&status); i=WEXITSTATUS(status); printf("Process ID of the waiting process(pid)is:%d ,end_state:%d\n",wpid,i); } } 改写程序,在子程序中用函数system启动一个较长时间运行的任务,而在父进程中执行完成任务后,应用waitpid函数等待子进程,子进程退出后父进程才退出。
时间: 2024-03-30 07:39:34 浏览: 199
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
pid_t pid, wpid;
int status, i;
pid = fork();
if (pid == 0) {
printf("This is the child process, process number(pid) is:%d\n", getpid());
system("sleep 10"); // 在子进程中执行一个较长时间的任务
exit(6);
} else {
printf("This is the parent process, waiting for the child process to finish...\n");
do {
wpid = waitpid(pid, &status, WUNTRACED); // 等待子进程退出
} while (!WIFEXITED(status) && !WIFSIGNALED(status)); // 如果子进程没有正常退出或被信号中断,则继续等待
i = WEXITSTATUS(status);
printf("Process ID of the waiting process(pid) is:%d, end_state:%d\n", wpid, i);
}
return 0;
}
阅读全文
相关推荐


















