内核作业补充

内核作业补充,第1张

内核作业补充 编写两个程序,一个是服务者程序,一个是客户程序,执行两个进程之间通过消息机制进行通信,消息表示msgkey可以使用常量定义,以便双方都可以利用。客户端将自己的进程号和父进程发送给服务器端,服务器端进程收到消息后,将自己的进程号和父进程号发给客户,然后返回。客户端收到后回显服务器端的pid和ppid,结束

客户进程

#include
#include
#include
#include
#include
#define MSGKEY 75

struct msgform{//发送的内容
	long mtype;
	char mtext[256];
};

int main(){
	struct msgform msg;
	

	//装填自己的信息包,准备发送
	msg.mtype=1;
	//制作mtext
	int *p;
	p=(int *)msg.mtext;
	int pid=getpid();
	*p=pid;//往载荷中放上自己的ProcessId
	
	int msgpid=msgget(MSGKEY,0777);
	msgsnd(msgpid,&msg,sizeof(int),0);//发送

	msgrcv(msgpid,&msg,256,pid,0);//接受信息
	printf("客户机: 从%d服务器收到了应答n",* p);//取出载荷的内容并显示	
	
	return 0;
}

服务器进程

#include
#include
#include
#include
#include
#define MSGKEY 75

struct msgform{//发送的内容
	long mtype;
	char mtext[256]; 
};

int msgpid;
int main(){
	extern cleanup();
	for(int i=0;i<20;i++)
		signal(i,cleanup);	//设置软中断信号处理程序
	

	//====================== 监听==========================
	msgpid=msgget(MSGKEY,0777|IPC_CREAT); //初始化消息队列
	for(;;){				//一直接收消息
		struct msgform msg;
		msgrcv(msgpid,&msg,256,1,0);//接受信息
		int *p=(int*)msg.mtext;//载荷指针
		
		int pid=*p;//取出载荷的内容并显示
		printf("服务器: 从%d收到了它自己发送的pidn",pid);

		//装填自己的信息包,准备发送
		msg.mtype=pid;
		*p=getpid();//往载荷中放上自己的ProcessId
		msgsnd(msgpid,&msg,sizeof(int),0);//发送信息
	}


	return 0;
}

cleanup(){
	msgctl(msgpid,IPC_RMID,0);
	exit(1);
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5720634.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存