linux kernel character drivers

Linux内核的字符驱动程序

问题 (Question)

I have registered a character driver using the api register_chrdrv().

The driver creates an entry in /dev/myfile. User space applications can access my driver by opening the /dev/myfile. Now I want to make my character driver such that only one user space application can access my driver at a time; only when that user space application closes the file can another user space program access my driver.

Can this be done in the kernel level?

I don't have control of the number of applications running in user space so i have to make changes only in kernel level.

我已经注册了一个字符驱动程序使用的APIregister_chrdrv()

驱动程序创建了一个条目/dev/myfile用户空间的应用程序可以访问我的司机打开/ dev / MyFile.txt。现在我想让我的字符驱动程序,只有一个用户空间的应用程序可以访问一次我的司机;只有当用户空间应用程序关闭该文件可以另一个用户空间程序访问我的司机。可以在内核级别?

我没有在用户空间运行的应用程序的数量控制,所以我只能在内核级的改变。

我没有在用户空间运行的应用程序的数量控制,所以我只能在内核级的改变。

最佳答案 (Best Answer)

With a kernel char device you usually have the following methods.

.open
.read
.write
.release

(struct file_operations fops which will be used in the method register_chrdev(...,&fops).)

I would create your clients in a way that they open the device when they get started, and release it upon exiting. Like this you could easily handle / hinder a new (second) program of doing reads and writes on this device.

There may be other possibilities as well.

一个内核的字符设备通常有以下方法。

.open
.read
.write
.release

(结构file_operations FOPS中所要使用的方法register_chrdev(……,和FOPS)。)

我会创造你的客户的方式,他们打开设备时,他们开始在退出,并释放它。这样你可以很容易地处理/阻碍新的(二)程序在读取和写入该设备。

可能有其他的可能性,以及。

答案 (Answer) 2

As per your question you want to synchronize your application so that at a time only one process can access it. You can go for semaphore in kernel or locking methods in drivers that may help you. You may refer this http://www.cs.fsu.edu/~baker/devices/lxr/http/source/linux/kernel/semaphore.c

根据你的问题你想同步您的应用程序,在一个时间只有一个进程可以访问它。你可以去semaphore in kernellocking methods in drivers这可以帮助你。你可以参考这个HTTP:/ / www.cs。FSU。教育/ ~贝克/设备/ LXR / HTTP /来源/ Linux /核心/ C信号。

答案 (Answer) 3

In the open method of your driver: use a global flag to say whether the device is in use. Unset when closed (in the release method). Pseudo-code:

am_open=False

open() method:
if (!am_open)
  am_open=True
  ...proceed...
else
  return -EAGAIN; // try again later
 -or-
  return -EBUSY;


release() method:
  am_open=False

Having said that, drivers (usually) should be a 100% reentrant :)

在你的驱动的方法打开:使用全局标志表示设备是否在。撤消关闭时(在释放法)。伪:

am_open=False

open() method:
if (!am_open)
  am_open=True
  ...proceed...
else
  return -EAGAIN; // try again later
 -or-
  return -EBUSY;


release() method:
  am_open=False

不得不说的是,司机(通常)应该是一个100%折返:)

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/23436827