- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
- 4、该文档为VIP文档,如果想要下载,成为VIP会员后,下载免费。
- 5、成为VIP后,下载本文档将扣除1次下载权益。下载后,不支持退款、换文档。如有疑问请联系我们。
- 6、成为VIP后,您将拥有八大权益,权益包括:VIP文档下载权益、阅读免打扰、文档格式转换、高级专利检索、专属身份标志、高级客服、多端互通、版权登记。
- 7、VIP文档为合作方或网友上传,每下载1次, 网站将根据用户上传文档的质量评分、类型等,对文档贡献者给予高额补贴、流量扶持。如果你也想贡献VIP文档。上传文档
查看更多
201321121054-陈孙伟-实验三
集美大学计算机工程学院实验报告
课程名称:操作系统
班级:计算1311 学号:201321121054 姓名:陈孙伟 实验编号:实验三
一、目的
理解线程与进程的概念
掌握线程与进程在组成成分上的差别以及与其相适应的通信方式与应用目标。二、内容系统进程和线程机制为背景,掌握fork()和clone)系统调用的与功能,以及与其相适应的高级通信方式。fork()派生的子进程之间通过pipe通信,clone()创建的线程之间通过共享内存通信,对于后者需要考虑互斥问题。
生产者——消费者问题为例,通过理解fork()与clone()两个系统调用的区别程序能够创建进程或线程,其中包括两个生产者和两个消费者,生产者和消费者之间能够传递数据。fork()系统调用
基于clone()系统调用
fork参考代码;
#include sys/types.h
#include sys/file.h
#include unistd.h
#include stdio.h
#include string.h
#include stdlib.h
char r_buf[4];
char w_buf[4];
int pipe_fd[2];
pid_t pid1,pid2,pid3,pid4;//定义4个进程
int producer(int id);//生产者
int consumer(int id);//消费者
int main(int argc,char **argv)
{
if(pipe(pipe_fd)0)
{
printf(pipe create error \n);
exit(-1);
}
else
{
printf(pipe is created successfully!\n);
if((pid1 = fork())==0)
producer(1);
if((pid2 = fork())==0)
producer(2);
if((pid3 = fork())==0)
consumer(1);
if((pid4 = fork())==0)
consumer(2);
}
close(pipe_fd[0]);
close(pipe_fd[1]);
int i,pid,status;
for(i=0;i4;i++)
pid=wait(status);
exit(0);
}
int producer(int id)
{
printf(producer %d is running!\n,id);
close(pipe_fd[0]);
int i=0;
for(i=1;i10;i++)
{
sleep(3);
if(id==1)
strcpy(w_buf,aaa\0);
else
strcpy(w_buf,bbb\0);
if(write(pipe_fd[1],w_buf,4)==-1)
printf(write to pipe error\n);
}
close(pipe_fd[1]);//关掉管道文件的写
printf(producer %d is over! \n,id);
exit(id);
}
int consumer(int id)
{
close(pipe_fd[1]);//管道文件的写
printf(producer %d is running! \n,id);
if(id==1)
strcpy(w_buf,ccc\0);
else
strcpy(w_buf,ddd\0);
while(1)
{
sleep(1);//一个消费者读取管道后sleep,给另一个消费者运行的机会
strcpy(r_buf,eee\0);
if(read(pipe_fd[0],r_buf,4)==0)
break;
printf(consumer %d get %s,while the w_buf is %s\n,id,r_buf,w_buf);
}
close(pipe_fd[0]);
printf(consumer %d is over! \n,id);
exit(id);
}
Clone系统参考代码:
#includesched.h
#includepthread.h
#includestdio.h
#includestdlib.h
#includestring.h
#includesemaphore.h
int producer(void *args);
int consumer(void *args);
pthread_mutex_t mutex;
sem_t product;
sem_t warehouse;
char buf
文档评论(0)