can kernel identify which userapp got killed/closed, among few apps it is serving

85 Views Asked by At

I'm writing a linux kernel driver, which creates a char device file "/dev/my_file". Multiple userspace applications do open() of this file and use the ioctl cmd provided to register app specific data. IOCTL also provides for deregister cmd, which apps can use and deregister themselves(kernel drv removes app data, delete any memory allocation etc) when doing clean exit. However, if an application gets killed after doing open() and ioctl register cmd. How the driver can detect which app got killed and then carry out cleanup task for removing app specific data. I know the .release func ptr from struct file_operations is called and driver is notified, but not sure on how the drv can find the specific app that got killed.

Thanks Sheetal

1

There are 1 best solutions below

0
On

Cleaning up on the "app" (or process) level is tricky because the process context that calls the .release() handler is not necessarily the same one that called the .open() handler. (For example, the process that called open() could fork a child process and exit, leaving the child running as a daemon process.)

I would recommend cleaning up on an "open file description" level instead. Every successful open() call creates an open file description, and the .release() handler is called when there are no more references to that open file description. You can use the private_data member of struct file to point to a private data structure allocated by the .open() handler. That "open file specific" data structure can have a member that points to your device-specific, private data structure.

As a practical example, I did the above in the kernel code for the "Comedi" subsystem. Its .open() handler comedi_open() (see drivers/staging/comedi/comedi_fops.c) allocates a struct comedi_file (which the struct file's private_data member will point to), and the struct comedi_file contains a pointer (member dev) to the device's private data of type struct comedi_device. Other members of struct comedi_file contain information that can vary on a "per open file" basis that is not shared with other open()s of the same file. The struct comedi_file allocated by comedi_open() is freed by the .release() handler comedi_close() (which I ought to rename to comedi_release sometime!).