《操作系统》上机实验一报告.doc
文本预览下载声明
《操作系统》上机实验一报告
目录
一、实验关键问题
二、代码设计思路
三、实现的关键代码
四、程序运行结果
五、实验总结
实验关键问题
1.1 要求:编写一个Linux系统C程序,由父亲创建2个子进程,再由子进程各自从控制台接收一串字符串,保存在各自的全局字符串变量中,然后正常结束。父进程调用waitpid等待子进程结束,并分别显示每个子进程的进程标识号和所接收的字符串。
1.2 要求:父进程创建一子进程,父进程向子进程发送数据,子进程接收数据,并写入文件。
代码设计思路
2.1 问题1.1的代码设计思路
由父进程创建两个共享内存→分别创建两个子进程→提示用户输入信息,并将信息存到子进程各自对应的共享内存中→等待子进程结束→子进程结束后,父进程被唤醒并与共享内存连接→分别从这两个内存共享中获取数据,并把数据和对应的子进程PID输出到屏幕上→父进程结束
2.2 问题1.2的代码设计思路
由父进程创建管道→创建子进程→父进程关闭读管道,获取用户输入的数据→把数据写入写管道中,关闭写管道→等待子进程结束,此时父进程挂起→子进程关闭写管道→子进程读取父进程放入读管道中的数据,显示数据到屏幕上→将数据写入文件“CP_file.txt”中→关闭读管道,关闭文件→结束子进程→父进程被唤醒后父进程也结束。
实现的关键代码
3.1 问题1.1的实现代码
#include unistd.h
#include sys/ipc.h
#include sys/shm.h
#include sys/types.h
#include sys/wait.h
#include stdio.h
#include stdlib.h
#define Key0 9876
#define Key1 5432
#define Size 2048 //Size表示共享内存大小,此处设置为2048
int main()
{
int shmid1, shmid2;//共享内存的标识符
//父进程创建共享内存shmid1和shmid2
shmid1 = shmget(Key0, Size, IPC_CREAT|0600);
shmid2 = shmget(Key1, Size, IPC_CREAT|0600);
pid_t pid1, pid2;//子进程标识符
char *shmaddr;//连接地址
//父进程创建子进程pid1
if ((pid1 = fork()) == 0)
{
shmaddr = (char*)shmat(shmid1, NULL, 0);/*shmat()实现子进程pid1与共享内存shmid1的连接*/
printf(Child process 1 is running now, enter a string:);/*请求用户输入一个字符串*/
fgets(shmaddr, Size-1, stdin);/*fgets()将信息存到shmaddr所指的内存空间*/
shmdt(shmaddr);/*shmdt()使该进程脱离该共享内存断,但并不删除该内存段*/
return 0;
}
printf(\nWaitting for child process 1...\n);
waitpid(pid1, NULL, 0);//等待子进程pid1结束
printf(Child process 1 is over...\n);
//父进程创建子进程pid2
if ((pid2 = fork()) == 0)
{
shmaddr = (char*)shmat(shmid2, NULL, 0);
printf(Child process 2 is running now, enter a string:);
fgets(shmaddr, Size-1, stdin);
shmdt(shmaddr);
return 0;
}
printf(\nWaitting for chils process 2...\n);
waitpid(pid2, NULL, 0);
printf(Child process 2 is over...\n\n);
shmaddr = (char*)shmat(shmid1, NULL, 0); /*父进程与共享内存shmid1连接*/
printf(Child process 1: PID=%d message: %s\n, pid1, shmaddr);/*屏幕显示共享内存shmid1的信息*/
shmdt(shmaddr);
shmctl(shmid1, IPC_RMID, NULL);//删除共享内存shmid1
shmaddr = (char*)shmat(shmid2, NUL
显示全部