2024-8-14文件IO课后作业

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 msgbuf{
	long mtype;
	char mtext[100];
}buf;
int main(int argc, const char *argv[])
{
	//1.创建key值
	key_t key=ftok("./",1);
	if(-1==key)
	{
		perror("创建key值失败");
		return -1;
	}
	//2.创建消息队列
	int msg_id=msgget(key,IPC_CREAT | 0777);
	if(-1==msg_id){
		perror("创建队列失败");
		return -1;
	}
	//3.通过键盘制定消息标识并发送消息
		printf("请输入消息标识:");
		long a;
		scanf("%ld",&a);
		buf.mtype=a;
		getchar();
	while(1){
		memset(buf.mtext,0,sizeof(buf.mtext));
		fgets(buf.mtext, sizeof(buf.mtext), stdin);
		int msg_ret = msgsnd(msg_id,&buf,strlen(buf.mtext),0);
		if(-1==msg_ret){
			perror("发送消息失败");
			return -1;
		}
		if(strcmp(buf.mtext,"bye\n")==0){
			break;
		}
	}
	return 0;
}

2.接受消息

#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 msgbuf{
    long mtype;
    char mtext[100];
}buf;
int main(int argc, const char *argv[])
{
    //1.创建key值
    key_t key=ftok("./",1);
    if(-1==key)
    {
        perror("创建key值失败");
        return -1;
    }
    //2.创建消息队列                                                  
    int msg_id=msgget(key,IPC_CREAT | 0777);
    if(-1==msg_id){
        perror("创建队列失败");
        return -1;
    }
    //3.通过键盘制定消息标识并接受消息
        printf("请输入要接收的消息类型(整数): ");
        long a;
        scanf("%ld", &a);
        getchar();
    while(1){
        memset(buf.mtext,0,sizeof(buf.mtext));
        int msg_ret = msgrcv(msg_id,&buf,sizeof(buf.mtext),a,0);
        if(-1==msg_ret){
            perror("接受消息失败");
            return -1;
        }
        printf("%s",buf.mtext);
        if(strcmp(buf.mtext,"bye\n")==0){
            break;
        }
    }
    return 0;
}
                                                                      
 

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值