进程控制
编写多进程程序,掌握fork()、exec()、wait()和waitpid()等函数的使用,进一步理解在Linux中多进程编程的步骤,要求:
程序有3 个进程,其中一个为父进程,其余两个是该父进程创建的子进程,其中一个子进程运行“ls -l”指令,另一个子进程在暂停5s 之后异常退出,父进程先用阻塞方式等待第一个子进程的结束,然后用非阻塞方式等待另一个子进程的退出,待收集到第二个子进程结束的信息,父进程就返回;
/* multi_ proc_ wrong.c文件*/
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
int main( ){
pid_t child1,child2,child;
/*创建两个子进程*/
child1=fork();
child2=fork();
/*子进程1的出错处理*/
if(child1==-1){
printf("Child1 fork error \n");
exit(1);/*异常退出*/
}
/*在子进程1中调用execlp()函数*/
else if(child1==0){
printf("I am child1 and I execute 'ls -l'\n");
if(execlp("ls","ls","-1",NULL)<0){
printf("Child1 execlp error\n");
}
/*子进程2的出错处理*/
if(child2==-1){
printf("Child2 fork error\n");
exit(1); /*异常退出*/
}
/*在子进程2中使其暂停5s*/
else if( child2==0){
printf("I am child2.I will sleep for 5 seconds!\n");
sleep(5);
printf("I am child2.I have awaked and I will exit!\n");
exit(0); /*正常退出*/
}
/*在父进程中等待两个子进程的退出*/
else{
printf("I am father progress\n");
child=waitpid(child1,NULL,0);/*阻塞式等待*/
if(child==child1){
printf("I am father progress.I get child1 exit code :%d\n",child);
}
else{
printf("Error occured!\n");
}
do{
child=waitpid(child2,NULL,WNOHANG);/*非阻塞shi等待*/
if( child==0){
printf("I am father progress.The child2 progress has not exited!\n" );
sleep(1);
}
}while(child==0);
if(child==child2)
{
printf("I am father progress.I get child2 exit code: %d\n",child);
}
else{
printf("Erroe occured!\n");
}
}
}
exit(0);
}
特别注意:
仅供参考学习,转载请附上原文链接
图片来源于网络、个人收藏、个人制作、老师PPT
该篇文章不做任何商业用途,纯属分享学习心得,如有侵权,望联系本人处理
还在读大学的程序员,项目经验少,如有纰漏,感谢指正
需要源代码请私聊联系本人
谢谢配合
如果这篇文章对您有帮助,小小的点个赞,算是给小学弟的鼓励吧!谢谢大佬!!/呱呱.jpg