实验一进程创建 并发执行.doc_第1页
实验一进程创建 并发执行.doc_第2页
实验一进程创建 并发执行.doc_第3页
实验一进程创建 并发执行.doc_第4页
免费预览已结束,剩余1页可下载查看

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

实验一:进程创建、并发执行一、 实验目的 加强对进程概念的理解 进一步了解并发执行的实质二、 实验内容1、 利用fork()函数创建子进程。2、 考察fork()函数创建的子进程与父进程之间的同名变量是否为临界资源。3、 利用fork()函数编写一个程序,要求父进程创建两个子进程,父进程、子进程并发执行,输出并发执行的消息。 三、 实验环境 PC + Linux Red Hat操作系统 GCC四、 实验原理及实验思路 fork()功能:创建一个新的进程语法:#include #include pid_t fork();说明:本系统调用为调用进程(也称父进程)创建一子进程。事实上,子进程是父进程的一个“复制品”。父子进程为独立进程,平等调度,用户空间独立 。返回值:调用成功,则返回两次。对子进程返回0,对父进程返回子进程号,这也是最方便的区分父子进程的方法。调用失败则返回-1给父进程,子进程不生成kill()功能:杀死执行中的进程语法:#include #include void kill(pid_t pid,int signo);说明:pid为要被杀死的进程id,signo可以置为SIGINT或SIGTERM。 返回值:等待到一个子进程返回时,返回值为该子进程号,同时stat_loc带回子进程的返回状态信息(参考exit)。若无子进程,则返回值为-1。五、 流程图 六、源代码 Lab1-1:#include #include #include main() pid_t child; printf(“Forking.n);child =fork(); if (child0) perror(Fork failed!n); exit(1); else if (child=0) printf(Im the child!n); else printf(Im the parent!n); printf(Why Im printed twice?n);Lab1-2:#include #include #include main() pid_t child; int a=0; printf(Forking.n);child=fork(); if (child0) perror(Fork failed!n); exit(1); else if (child=0) a+; printf(Child:a=%dn,a); else a+; printf(Parent:a=%dn,a); Lab1-3:#include unistd.h#include sys/types.h#include signal.h#include stdio.hint main(int argc,char* 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 waiting to be killedn); else printf(this is farther process, after first forkn); /*fork*/ printf(second forkn); child2_pid = fork(); if(child2_pid 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. Im the child! Why Im printed twice? Lab1-2:输出:Forking. Child a1 Lab1-3:输出:first fork this is the first child process the first child proc waiting to be killed this

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论