赞
踩
代码:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
int main(){
int pid;
pid=fork(); /* 创建子进程 */
switch(pid){
case -1: /* 创建失败 */
printf("fork fail!\n");
exit(1);
case 0: /* 子进程*/
printf("Child process PID:%d.\n",getpid());
execlp("/bin/ls","ls",NULL); /* 装载子进程映像 ls 命令*/
printf("exec fail!\n");
exit(1);
default: /* 父进程*/
printf("Parent process PID: %4d.\n",getpid());
wait(NULL); /* 父进程等待子进程运行完毕 */
printf("ls completed !\n");
exit(0);
}
return 0;
}
结果:
问题1:该程序中一共有几个进程并发?
两个,父进程和子进程(应该是吧)
问题2:wait(NULL)起到了什么作用,如果删除会出现什么情况,为什么?
wait()调用后立即阻塞自己,直到当前进程的某个子进程退出。其参数用来保存被收集进程退出时的一些状态,它是一个指向int类型的指针。但如果我们对这个子进程是如何死掉的毫不在意,只想把这个僵尸进程消灭掉,我们就可以设定这个参数为NULL。
代码:
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
int main(){
int status;
pid_t pc,pr;
pc=fork();
if(pc<0)
printf("error ocurred!\n");
else if(pc==0){
printf("This is child process with pid of %d.\n",getpid());
exit(3);
}
else{
pr=wait(&status);
if(WIFEXITED(status)){
printf("the child process exit normally.\n");
printf("the return code is %d.\n",WEXITSTATUS(status));
}
else
printf("the child process exit abnormally.\n");
}
}
结果:
问题1:该程序中的pr变量的值代表的什么含义?
pr的值代表子进程的pid
问题2:如果程序中出现出现exit(0)和exit(1)代表什么意思?
exit(0)表示进程正常终止,exit(1)表示进程运行有错,异常终止
代码:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
int main(){
int status;
pid_t pid = fork();
if(pid<0){
printf("error ocurred!\n");
}
else if(pid==0){
printf("This is child process with pid of %d.\n",getpid());
sleep(5);
exit(0);
}
else{
printf("Parent process PID: %4d.\n",getpid());
wait(&status);
printf("the child return code is %d.\n",WEXITSTATUS(status));
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。