实验四 进程管理
实验目标
- 加深对进程概念的理解,明确进程与程序的区别;
- 进一步认识并发执行的实质
- 掌握进程管理、进程通信
实验内容
- 【实验4-1】 进程创建
- 【实验4-2】进程控制
- 【实验4-3】进程的管道通信
【实验4-1】进程的创建
知识点回顾
- Linux进程API实现
功能描述
- 使用进程创建fork函数,创建子进程
实验步骤
- 编写一段程序,使用系统调用fork()创建两个子进程。
当此程序运行时,在系统中有一个父进程和两个子进程活动。让每一个进程在屏幕上显示一个字符:父进程显示“a“;子进程分别显示字符”b“和字符“c”。试观察记录屏幕上的显示结果,并分析原因。
- 代码编写
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
if(fork() == 0)
{
printf("b\n");
exit(0);
}
else
{
if(fork() == 0)
{
printf("c\n");
exit(0);
}
printf("a\n");
exit(0);
}
}
实验现象
【实验4-2】进程控制
知识点回顾
- Linux进程API实现
功能描述
- 修改已编写的程序,将每一个进程输出一个字符改为每一个进程输出一句话,再观察程序执行时屏幕上出现的现象,并分析原因
实验步骤
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
if(fork() == 0)
{
printf("this is son's one process\n");
exit(0);
}
else
{
if(fork() == 0)
{
printf("this is son's two process\n");
exit(0);
}
printf("this is father process\n");
exit(0);
}
}
实验现象
【实验4-3】进程的管道通信
知识点回顾
- Linux进程API实现
功能描述
- 编写程序实现进程的管道通信。使用系统调用pipe()建立一个管道,二个子进程P1和P2分别向管道各写一句话:
- Child 1 is sending a message!
- Child 2 is sending a message!
- 父进程从管道中读出二个来自子进程的信息并显示(要求先接收P1,再接收P2)。
实验步骤
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include<string.h>
int pid1,pid2;
main( )
{
int fd[2];
char outpipe[100],inpipe[100];
pipe(fd);
while ((pid1=fork( ))==-1);
if(pid1==0)
{
lockf(fd[1],1,0);
sprintf(outpipe,"child 1 process is sending message!");
write(fd[1],outpipe,50);
sleep(1);
lockf(fd[1],0,0);
exit(0);
}
else
{
while((pid2=fork( ))==-1);
if(pid2==0)
{
lockf(fd[1],1,0);
sprintf(outpipe,"child 2 process is sending message!");
write(fd[1],outpipe,50);
sleep(5);
lockf(fd[1],0,0);
exit(0);
}
else
{
wait(0);
read(fd[0],inpipe,50);
printf("%s\n",inpipe);
wait(0);
read(fd[0],inpipe,50);
printf("%s\n",inpipe);
exit(0);
}
}
}
实验现象
实现报告
实现报告
链接:https://pan.baidu.com/s/1dyMw_n8OnwSsYiv_hWWGpw
提取码:rin2
复制这段内容后打开百度网盘手机App,操作更方便哦
本文作者为一木,转载请注明。