进程通信-消息机制(实验5)

进程通信-消息机制

1.实验目的
① 了解和掌握linux操作系统的基本操作
② 了解并掌握进程通信中消息机制的工作原理
2.实验平台
操作系统:Linux
3.实验内容和要求
(一)操作实验任务
① 学习使用文本编辑工具vi
② 使用ifconfig命令查看当前网络配置情况
③ 使用netstat命令查看网络连接情况和运行端口
④ 了解itables命令设置防火墙
⑤ 使用lspci查看当前机器的硬件设备配置
⑥ 使用more /proc/cupinfo查看cpu信息
⑦ 使用reboot重启电脑,采用halt或shutdown 关闭电脑。
(二)编程实验任务
① 编写一个程序,使用系统调用msgget(), msgsnd(), msgrcv(), msgctl()实现消息的发送和接收,一个子进程发送10条消息,一个子进程接收10条消息。(MSGKEY取值75,消息的长度取1024)
实验内容与完成情况:

  • 操作实验任务

① 使用ifconfig命令查看当前网络配置情况

root@kali:~# ifconfig

② 使用netstat命令查看网络连接情况和运行端口

root@kali:~# netstat -a
root@kali:~# netstat -i
root@kali:~# netstat -n

③ 了解ipables命令设置防火墙

  • 查看当前系统的iptables规则
root@kali:~# iptables -L
  • 查看每个链的默认规则
root@kali:~# iptables -S
  • 清空已有的规则集
root@kali:~# iptables -F
  • 配置服务器允许SSH连接
root@kali:~# iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
  • 接受ssh、http、mysql的连接,端口号分别为22、80、3306端口
    故需要通过以下三条命令
root@kali:~# iptables -A INPUT -p tcp --dport 22 -j ACCEPT
root@kali:~# iptables -A INPUT -p tcp --dport 80 -j ACCEPT
root@kali:~# iptables -A INPUT -p tcp --dport 3306 -j ACCEPT
  • 保证我们的VPS能够正常运行,还需要添加一条允许规则。通常,计算机上的服务都会发送网络数据包以保持彼此之间的通信。而这种通信会利用到一个名叫loopback的伪网卡将流量引导回自己。因此,
  • 我们还需要为loopback网卡添加一条允许规则
root@kali:~# iptables -I INPUT 1 -i lo -j ACCEPT
  • 将INPUT链的默认规则更改为“Drop”即丢弃
root@kali:~# iptables -P INPUT DROP
  • 将这些配置添加到配置文件当中,以保证系统在下次重启后会自动载入我们的
    IPTables防火墙规则
root@kali:~# apt-get update
root@kali:~# apt-get install iptables-persistent

④ 使用lspci查看当前机器的硬件设备配置

root@kali:~# lspci

⑤ 使用more /proc/cpuinfo查看cpu信息
使用cat的话会显示一次性显示出来,而more只会显示一页。

root@kali:~# more /proc/cpuinfo
root@kali:~# cat /proc/cpuinfo

⑥ 使用reboot重启电脑,采用halt或shutdown 关闭电脑。

 - root@kali:~# shutdown -h now  立刻关机
 - root@kali:~# halt   立刻关机
 - root@kali:~# shutdown -h 10 10分钟后自动关机
 - root@kali:~# reboot  重启
 - root@kali:~# shutdown -r now 立刻重启
 - root@kali:~# shutdown -r 1010分钟自动重启
 - root@kali:~# shutdown -r 20:00 在时间为20:00时候重启

编写一个程序,使用系统调用msgget(), msgsnd(), msgrcv(), msgctl()实现消息的发送和接收,一个子进程发送10条消息,一个子进程接收10条消息。(MSGKEY取值75,消息的长度取1024)

代码如下:

#include <stdio.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>
#define MSGKEY 75

struct msgform
{
	long mtype;
	char mtrex[1030];
}msg;

int msgqid,i;

int CLIENT()				
{
	int i;
	msgqid=msgget(MSGKEY,0777);
	for(i=10;i>=1;i--)
	{
		msg.mtype=i;
		printf("(client)sent\n");
		msgsnd(msgqid,&msg,1024,0);
	}
	exit(0);
}

int SERVER()				
{
	msgqid=msgget(MSGKEY,0777|IPC_CREAT);		
	do
	{
		msgrcv(msgqid,&msg,1030,0,0);
		printf("(server)received\n");
	}while(msg.mtype!=1);
	msgctl(msgqid,IPC_RMID,0);
	exit(0);
}

int main()
{
	while((i=fork())==-1);
	if(!i)
		SERVER();		
	while((i=fork())==-1);
	if(!i)
		CLIENT();		
	wait(0);
	wait(0);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/YZ_TONGXIE/article/details/106740686