网络编程第五次作业(2024.8.14)

1.

#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>

struct message{
	long mytype;             //消息标识
	char data[100];          //数据
}buf;

int main(int argc, const char *argv[]){
	//1.创建键值
	key_t key = ftok("./",1);
	if(-1 == key){
		printf("创建键值失败!\n");
		return -1;
	}
	//创建消息队列
	int mes_num = msgget(key,IPC_CREAT | 0777);
	if(mes_num == -1){
		printf("创建消息队列失败!\n");
		return -1;
	}
	//往消息队列里面发送消息
	while(strcmp(buf.data,"end\n")){
		printf("请输入一个整数作为标识\n");
		scanf("%ld",&buf.mytype);
		getchar();
		memset(buf.data,0,sizeof(buf.data));
		printf("请输入要传输的内容\n");
		fgets(buf.data,sizeof(buf.data)-1,stdin);
		//默认是阻碍的发送
		int send = msgsnd(mes_num,&buf,sizeof(buf),0);
		if(-1 == send){
			printf("发送失败!\n");
			return -1;
		}
	}
	return 0;
}

#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>

struct message{
	long mytype;             //消息标识
	char data[100];          //数据
}buf;

int main(int argc, const char *argv[]){
	//1.创建键值
	key_t key = ftok("./",1);
	if(-1 == key){
		printf("创建键值失败!\n");
		return -1;
	}
	//创建消息队列
	int mes_num = msgget(key,IPC_CREAT | 0777);
	if(mes_num == -1){
		printf("创建消息队列失败!\n");
		return -1;
	}
	//往消息队列里面发送消息
	while(strcmp(buf.data,"end\n")){
		printf("请输入一个整数作为接收标识\n");
		scanf("%ld",&buf.mytype);
		getchar();
		memset(buf.data,0,100);
		int rcv = msgrcv(mes_num,&buf,sizeof(buf),buf.mytype,0);
		if(-1 == rcv){
			printf("接收失败!\n");
			return -1;
		}
		printf("接收数据为:%s\n",buf.data);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值