实验7-编写多进程程序.pdfVIP

  • 3
  • 0
  • 约1.09万字
  • 约 18页
  • 2020-11-12 发布于湖北
  • 举报
实验 7- 编写多进程程序 实验七 编写多进程程序 学生姓名: 李亚军 学 号: 6100412196 专业班级: 卓越计科 121班 1.实验目的 通过编写多进程程序,使读者熟练掌握 fork() 、exec() 、wait() 和waitpid() 等函数的使用,进一步理解在 Linux 中多进程编程的步骤。 2.实验内容 该实验有 3个进程,其中一个为父进程,其余两个是 该父进程创建的子进程,其中一个子进程运行 “ls -l ”指令,另一个子进程在暂停 5s之后异常退出,父进程 先用阻塞方式等待第一个子进程的结束,然后用非阻塞 方式等待另一个子进程的退出,待收集到第二个子进程 结束的信息,父进程就返回。 3.实验步骤 (1)画出该实验流程图 该实验流程图如图所示。 图 实验 7.1流程图 (2)实验源代码( multi_proc.c ) 先看一下下面的代码,这个程序能得到我们所希望的 结果吗,它的运行会产生几个进程?请读者回忆一下 fo rk() 调用的具体过程。 答:会产生四个进程 /* multi_proc_wrong.c */ #include stdio.h #include stdlib.h #include sys/types.h #include unistd.h #include sys/wait.h int main(void) { pid_t child1, child2, child; /* 创建两个子进程 */ child1 = fork(); child2 = fork(); /* 子进程 1的出错处理 */ if (child1 == -1) { printf(Child1 fork error\n); exit(1); } else if (child1 == 0) /* 在子进程 1中调用 execlp()函数*/ { printf(In child1: execute ls -l\n); if (execlp(ls, ls,-l, NULL)0) { printf(Child1 execlp error\n); } } if (child2 == -1) /* 子进程 2的出错处理 */ { printf(Child2 fork error\n); exit(1); } else if( child2 == 0 ) /* 在子进程 2中使其暂停 5s*/ { printf(In child2: sleep for 5 seconds and then exit\n); sleep(5); exit(0); } else /*在父进程中等待两个子进程的

文档评论(0)

1亿VIP精品文档

相关文档