简体   繁体   English

Python3以阻塞模式读取字符设备

[英]Python3 read fron character device in blocking mode

I wrote a character device driver.我写了一个字符设备驱动程序。 Now I want to use python to read from it when there is data.现在我想在有数据时使用 python 来读取它。 However, I found that the modules "io" as well as "os" do not block upon reading.但是,我发现模块“io”和“os”在阅读时不会阻塞。 The latter even when I set os.set_blocking(fd,true).后者即使我设置了 os.set_blocking(fd,true)。

Is there a way to access the device in blocking mode?有没有办法以阻止模式访问设备? Or do I miss something in the device driver (tail works fine)?还是我错过了设备驱动程序中的某些内容(尾部工作正常)?

f=io.open("/dev/tstty0","r")
while (1)
  data=str(f.read(32))
  print("mark") # <--- endless list of marks
  #do somthing

The read function of the device driver:读取设备驱动的function:

static ssize_t tstty_read(
  struct file *filp,
  char *buffer,
  size_t length,
  loff_t *offset)
{
  unsigned char b;
  unsigned long ofs=0;
  devConfig* dev=filp->private_data;
  if (dev)
  {
    while (fifoGet(&dev->tcp2dev,&b) && (ofs<length))
    {
      if (put_user(b,buffer+ofs))
      {
        printk(KERN_ERR "Could not copy user data");
        return -EINVAL;
      }
      ofs++;
    }
    //printk(KERN_INFO "Reading device");
    return ofs;
  }
  printk(KERN_ERR "Unknown device: %s",filp->f_path.dentry->d_iname);
  return -EINVAL;
};

The read function reads any bytes available from a fifo.读取 function 读取来自 fifo 的任何可用字节。 I none is available 0 is returned. I none is available 0 返回。

Kudos to Ian Abbott.向伊恩·阿博特致敬。 A character device has to implement the ability to block a read request.字符设备必须实现阻止读取请求的能力。 The read file operation has to evaluate filp->f_flags & O_NONBLOCK to check if a client has requested blocking I/O.读取文件操作必须评估 filp->f_flags & O_NONBLOCK 以检查客户端是否请求阻塞 I/O。

This link helped me with an example: simple linux driver code for blocking and non-blocking read这个链接帮我举了一个例子: simple linux driver code for blocking and non-blocking read

This example works but one has to consider two more things not covered in the example: a) What to do when you want to unload the driver while in read operation (just dont do it or wake up and abort)?此示例有效,但必须考虑示例中未涵盖的另外两件事:a) 当您想在读取操作时卸载驱动程序时该怎么办(只是不要这样做或唤醒并中止)? b) How to abort a client caught in blocking I/O? b) 如何中止陷入阻塞 I/O 的客户端?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM