- 1、本文档共8页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
Linux系统编程实验五:进程编程讲述
实验五:进程编程
实验目的:
学会fork、vfork函数的使用
学会调用wait和waitpid函数
实验要求:
(一)利用fork函数,编写一应用程序,在程序中创建一子进程,分别在父进程和子进程中打印进程ID
(二)使用vfork创建一子进程,让子进程睡眠1s,分别在父进程和子进程中打印进程ID,观察父子进程的运行顺序
(三)编写一应用程序,在程序中创建一子进程,父进程需等待子进程运行结束后才能执行
实验器材:
软件:安装了Linux的vmware虚拟机
硬件:PC机一台
实验步骤:
(一)fork函数的使用
1、编写实验代码fork_pid.c
#include stdio.h
#include unistd.h
#include errno.h
#include stdlib.h
int main(int argc, char *argv[])
{
pid_t child;
/*创建子进程*/
……
child=frok();
if(child==-1)//出错
printf(“error!”);
else if(child==0)//子进程中
printf(“I am the child:%d”child);
else if(child0)//父进程返回子进程号
printf(“I am the parent:%d”,child);
}
/****************************
#include stdio.h
#include unistd.h
#include errno.h
#include stdlib.h
int main(int argc, char *argv[])
{
pid_t child;
/*创建子进程*/
//……
child=fork();
if(child==-1)//出错
{
printf(error!);
exit(1);
}
else if(child0)//父进程返回子进程号
{
printf(I am the parent:%d\n,getppid());
exit(1);
}
else if(child==0)//子进程中
{
printf(I am the child:%d\n,getpid());
//exit(1);
}
return 0;
}*****************************/2、编译应用程序fork_pid.c
用gcc命令编译fork_pid.c后生成可执行文件fork_pid
3、运行应用程序
4、fork函数创建子进程后,父子进程是独立、同时运行的并没有先后顺序
(二)vfork创建子进程
1、编写实验代码vfork_pid.c
#include stdio.h
#include unistd.h
#include errno.h
#include stdlib.h
int main(int argc, char *argv[])
{
pid_t child;
/*创建子进程*/
if((child=vfork())==-1){
printf(fork error:%s\n,strerror(errno));
exit(1);
}
//子进程睡眠1s
……
else if(child==0)//子进程中
{
printf(I am the child:%d\n,getpid());
sleep(1);
exit(1);
}
else if(child0)//父进程返回子进程号
printf(I am the parent:%d\n,getppid());
return 0;
}
/***********-----------------
#include stdio.h
#include unistd.h
#include errno.h
#include stdlib.h
int main(int argc, char *argv[])
{
pid_t child;
child=vfork();
/*创建子进程*/
if(child==-1){
printf(error);
//printf(fork error:%s\n,strerror(errno));
exit(1);
}
else if(child==0)//子进程中
{
printf(I am the child:%d\n,getpid());
sleep(1);
printf(sleep finish!\n);
exit(1);
}
else if(chi
文档评论(0)