2024年2月7日发(作者:)
Linux进程控制实验报告
实验名称:
Linux进程控制
实验要求:
一.编写一个Linux系统C程序,由父亲创建2个子进程,再由子进程各自从控制台接收一串字符串,保存在各自的全局字符串变量中,然后正常结束。父进程调用waitpid等待子进程结束,并分别显示每个子进程的进程标识号和所接收的字符串。
二. 父进程创建一子进程,父进程向子进程发送数据,子进程接收数据,并写入文件。
关键问题: 一.需要用共享内存或使用vfork()函数创建子进程进行进程之间的数据共享及传递。父进程必须等待子进程结束才能继续执行。
二.注意信号的使用。子进程需等待父进程发送信号才执行相应操作。父,子进程之间的通信需要用到共享内存或者父进程用vfork()创建子进程。
设计思路: 一.使用共享内存实现数据共享,子进程一用shmaddr1保存输入的字符串,子进程二用shmaddr2保存字符串。父进程等待两个子进程分别输入完字符串,然后再分别把数据显示出来。
二.用共享内存的方法来实现父子进程之间的通信,首先建立共享内存区域,然后建立子进程,并让子进程等待父进程信号。在父进程中输入字符串,并把此字符串保存在共享内存区域,然后向子进程发出信号SIGUSR1,若子进程接受到SIGUSR1信号,则把父进程保存在共享内存区域的字符串取出,并把它写入文件。
关键代码:
一.
#include
#include
#include
#include
#include
#include
#include
#define KEY 1234
#define SIZE 64
char* shmaddr1;
char* shmaddr2;
main()
{
pid_t pid1;
pid_t pid2;
char* str1;
char* str2;
int shmid1;
int shmid2;
shmid1=shmget(23,SIZE,IPC_CREAT|0600);
shmid2=shmget(24,SIZE,IPC_CREAT|0600);
if ((pid1=fork())<0)
{
printf("creat 1 fail!n");
exit(0);
}
else if(pid1==0)
{
shmaddr1=(char*)shmat(shmid1,NULL,0);
printf("creat 1 successfully!n");
scanf("%s",str1);
printf("you enter:%sn",str1);
strcpy(shmaddr1,str1);
shmdt(shmaddr1);
exit(0);
}
wait();
if ((pid2=fork())<0)
{
printf("creat 2 fail!n");
exit(0);
}
else if(pid2==0)
{
shmaddr2=(char*)shmat(shmid2,NULL,0);
printf("creat 2 successfully!n");
scanf("%s",str2);
printf("you enter:%sn",str2);
strcpy(shmaddr2,str2);
shmdt(shmaddr2);
exit(0);
}
wait();
shmaddr1=(char*)shmat(shmid1,NULL,0);
shmaddr2=(char*)shmat(shmid2,NULL,0);
printf("one is %sn",shmaddr1);
printf("two is %sn",shmaddr2);
shmdt(shmaddr1);
shmdt(shmaddr2);
shmctl(shmid1,IPC_RMID,NULL);
shmctl(shmid2,IPC_RMID,NULL);
exit(0);
}
实验结果:
二.
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define key 1024
#define size 160
static void sign(int);
int shmid;
char* shmaddr;
main()
{
pid_t pid;
char str[20];
shmid=shmget(key,size,IPC_CREAT|0600);
if((pid=fork())<0)
{
perror("创建子进程错误!n");
exit(0);
}
else if(pid==0)
{
if(signal(SIGUSR1,sign)==SIG_ERR)
{
printf("SIGUSR1错误!n");
exit(0);
}
pause();
printf("子进程结束!n");
exit(0);
}
sleep(1);
shmaddr=(char*)shmat(shmid,NULL,0);
printf("请输入字符串:");
scanf("%s",str);
strcpy(shmaddr,str);
shmdt(shmaddr);
kill(pid,SIGUSR1);
wait();
shmctl(shmid,IPC_RMID,NULL);
}
static void sign(int signnum)
{
int fd;
char* shmaddr;
if(signnum==SIGUSR1)
{
printf("子进程接收到SIGUSR1.n");
shmaddr=(char*)shmat(shmid,NULL,0);
if((fd=open("",O_RDWR|O_CREAT|O_TRUNC))==-1)
{
printf("n打开文件错误!n");
return 0;
}
else
{
printf("写入:%sn",shmaddr);
write(fd,shmaddr,20);
close(fd);
}
shmdt(shmaddr);
}
}
实验总结: 经过此次实验,我学会了如何通过shm共享内存实现各进程间的数据共享,以及如何在父子进程之间发送信号和传输数据以及一些保存文件的操作,通过这次实验我受益良多。
本文发布于:2024-02-07 11:54:35,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170727807664721.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |