



下载本文档
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、实验一:进程创建、并发执行实验目的 加强对进程概念的理解 进一步了解并发执行的实质利用 fork() 考察 fork() 利用 fork()实验内容1、2、3、函数创建子进程。 函数创建的子进程与父进程之间的同名变量是否为临界资源。 函数编写一个程序,要求父进程创建两个子进程,父进程、子进程并发 执行,输出并发执行的消息。实验环境PC + Linux Red Hat 操作系统 GCC四、实验原理及实验思路fork()功能:创建一个新的进程语法: #include <unistd.h>#include <sys/types.h>pid_t fork();说明:本系统调用为
2、调用进程(也称父进程)创建一子进程。事实上,子进程是父进程 的一个 “复制品 ”。父子进程为独立进程,平等调度,用户空间独立 。 返回值:调用成功,则返回两次。对子进程返回0,对父进程返回子进程号,这也是最kill()功能:语法:方便的区分父子进程的方法。调用失败则返回 -1 给父进程,子进程不生成 杀死执行中的进程说明: 返回值:等待到一个子进程返回时,返回值为该子进程号,同时 返回状态信息(参考 exit )。若无子进程,则返回值为 -1。#include <sys/types.h> #include <signal.h> void kill(pid_t pid,i
3、nt signo); pid 为要被杀死的进程 id,signo 可以置为 SIGINT 或 SIGTERM 。stat_loc 带回子进程的五、流程图Izi六、源代码Lab1-1 :#include <unistd.h> #include <sys/types.h>#include <stdio.h> main()pid_t child;printf( “ Forkingn.".);child =fork();if (child<0)perror("Fork failed!n"); exit(1);else if (ch
4、ild=0)printf("I'm the child!n");elseprintf("I'm the parent!n");printf("Why I'm printed twice?n"); Lab1-2 :#include <unistd.h>#include <sys/types.h>#include <stdio.h>main()pid_t child;int a=0;printf("Forking.n"); child=fork();if (c
5、hild<0)perror("Fork failed!n"); exit(1);else if (child=0)a+; printf("Child:a=%dn",a);elsea+;printf("Parent:a=%dn",a);Lab1-3 :#include "unistd.h"#include "sys/types.h"#include "signal.h"#include "stdio.h" int main(int argc,char*
6、 argv) pid_t child1_pid,child2_pid;int i = 15;/*fork*/printf("first forkn");child1_pid = fork(); if(child1_pid < 0)printf("fork() fail!n");return -1;else if(child1_pid = 0)printf("this is the first child process n"); while(1)sleep(1);printf("the first child proc
7、 waiting to be killedn"); elseprintf("this is farther process, after first forkn"); /*fork*/ printf("second forkn"); child2_pid = fork(); if(child2_pid < 0) printf("fork() fail!n");return -1;else if(child2_pid = 0)printf("this is the second child process n&
8、quot;); while(1)sleep(1);printf("the second child proc waiting to be killedn"); elseprintf("this is farther process, after second forkn");while(i > 0)printf("after %d second,all proc will be killedn",i); sleep(2);i -= 2; /*kill*/ printf("kill the first child procn"); kill(child1_pid,SIGINT); printf("kill the second child procn"); kill(child2_pid,SIGINT); return 0;七、运行结果及其分析Lab1-1 :输出:Forking. I'm the child!八、Lab1-2 :输出:Lab1-3 :输出:Why I'm printed twice?Forking.Child a1first forkthis is the first child processthe f
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
评论
0/150
提交评论