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
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
main() { int p1,msgid,running=1; char buffer[BUFSIZ]; long int msg_to_receive=0; char *path=\; char *argv[3]={\,NULL};
5