【Linux】kernel与应用消息队列的一种设计

Linux进程间通讯的方式有很多种,这里介绍一种通过消息队列的方式来实现kernel与APP之间的消息收发实现方式,这种方式特别适用于,kernel中发送消息,应用层收取消息。

消息队列设备驱动

该方法的设计思路即是创建一个消息队列的设备,应用层通过该设备读取消息队列(通过一个线程);

static const struct file_operations com_kumsgq_fileops = {
    .read        = com_kumsgq_read,
    .poll        = com_kumsgq_poll,
    .release    = com_kumsgq_release,
};

int com_kumsgq_newfd(struct kumsgq *msgq, int flags)
{
	int ret, fd;
	struct kumsgfile *msgfile;

	if (((flags & O_ACCMODE) != O_RDONLY)
			|| (flags & ~(O_ACCMODE | O_NONBLOCK | O_CLOEXEC)))
		return -EINVAL;

	msgfile = kzalloc(sizeof(struct kumsgfile), GFP_KERNEL);
	if (!msgfile)
		return -ENOMEM;

	msgfile->msgq = msgq;
	INIT_LIST_HEAD(&msgfile->messages);
	spin_lock_init(&msgfile->messages_lock);

	ret = get_unused_fd_flags(O_RDWR | (flags & O_CLOEXEC));
	if (ret < 0)
		goto err_free_msgfile;
	fd = ret;

	msgfile->file = anon_inode_getfile("[com_kumsgq]", &com_kumsgq_fileops,
					msgfile, flags);
	if (IS_ERR(msgfile->file)) {
		ret = PTR_ERR(msgfile->file);
		goto err_put_fd;
	}

	fd_install(fd, msgfile->file);

	mutex_lock(&msgq->files_lock);

	list_add(&msgfile->list, &msgq->kumsgfiles);

	com_kumsgq_get(msgq);

	mutex_unlock(&msgq->files_lock);

	return fd;

err_put_fd:
	put_unused_fd(fd);
err_free_msgfile:
	kfree(msgfile);
	return ret;
}

驱动层插入消息到消息队列中,应用层创建一个线程从消息队列设备中读取消息。
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值