任艺锦操作系统实验报告 Linux进程创建与通信

2020-02-21 17:01

2011-2012学年第一学期

计算机操作系统实验报告

专 业:

班 级:

学 号: 姓 名:任艺锦 提交日期:2011年11月

1

实验二 Linux进程创建与进程通信

【实验目的】

1. 熟悉有关Linux系统调用;

2. 学习有关Linux的进程创建,理解进程创建后两个并发进程的执行; 3. 通过系统调用wait()和exit(),实现父子进程同步;

4. 掌握管道、消息缓冲等进程通信方法并了解其特点和使用限制。

【实验内容】

1. 父进程创建子进程

实现父进程创建一个子进程,返回后父子进程分别循环输出字符串“The parent process.”及“The child process.”5次,每次输出后使用sleep(1)延时一秒,然后再进入下一次循环。给出源程序代码和运行结果。

程序代码: main() {

int p1,i;

while ((p1=fork())==-1); if (p1>0) for (i=0;i<5;i++) { printf(\); sleep(1); }

else for (i=0;i<5;i++) { printf(\); sleep(1); } }

运行结果:

The parent process. The child process. The parent process. The child process. The parent process. The child process.

2

The parent process. The child process. The parent process. The child process. 2. 父子进程同步

修改上题程序,使用exit()和wait()实现父子进程同步,其同步方式为父进程等待子进程的同步,即:子进程循环输出5次,然后父进程再循环输出5次。给出源程序代码和运行结果。

程序代码: main() {

int p1,i;

while ((p1=fork())==-1); if (p1>0) { wait(0); for (i=0;i<5;i++) { printf(\); sleep(1); } } else { for (i=0;i<5;i++) { printf(\); sleep(1); } exit(0); } }

运行结果: I am parent. I am parent. I am parent. I am parent. I am parent. I am child. I am child. I am child. I am child. I am child.

3

3. Linux管道通信

编写一个程序,实现以下功能。给出源程序代码和运行结果。 (1)父进程使用系统调用pipe()创建一个无名管道; (2)创建两个子进程,分别向管道发送一条信息后结束;

子进程1发送:Child 1 is sending a message to parent! 子进程2发送:Child 2 is sending a message to parent!

(3)父进程从管道中分别接收两个子进程发来的消息并显示在屏幕上,父进程结束。两个子进程发送信息没有先后顺序要求。

源程序代码: #include #include #includemain() {

int p1,p2,fd[2]; char outpipe[50];

char inpipe1[50]=\; char inpipe2[50]=\; pipe(fd);

while((p1=fork())==-1); if (p1==0) { lockf(fd[1],1,0); write(fd[1],inpipe1,50); exit(0); } else {

while((p2=fork())==-1); if (p2==0) {

lockf(fd[1],1,0);

write(fd[1],inpipe2,50); exit(0); } else {

wait(0);

read(fd[0],outpipe,50);

4

lockf(fd[1],0,0);

printf(\); printf(\,outpipe); wait(0);

read(fd[0],outpipe,50); lockf(fd[1],0,0);

printf(\); printf(\,outpipe); exit(0); }

} }

运行结果:

Child 1 is sending a message to parent! Child 2 is sending a message to parent! 4. Linux消息缓冲通信

编写一个程序,实现以下功能。给出源程序代码和运行结果。

(1)父进程创建一个消息队列和一个子进程,由子进程发送消息,父进程等待子进程结束后接收子进程发来的消息,并显示消息内容。以“end”作为结束消息。

父进程:

#include #include #include #include

#include #include #include #define MAX_TEXT 512 struct my_msg { long int my_msg_type; char some_text[MAX_TEXT]; }msg;

main() { int p1,msgid,running=1; char buffer[BUFSIZ]; long int msg_to_receive=0; char *path=\; char *argv[3]={\,NULL};

5


任艺锦操作系统实验报告 Linux进程创建与通信.doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:题目与答案

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: