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
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 calledopen()
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 theprivate_data
member ofstruct 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()
handlercomedi_open()
(see drivers/staging/comedi/comedi_fops.c) allocates astruct comedi_file
(which thestruct file
'sprivate_data
member will point to), and thestruct comedi_file
contains a pointer (memberdev
) to the device's private data of typestruct comedi_device
. Other members ofstruct comedi_file
contain information that can vary on a "per open file" basis that is not shared with otheropen()
s of the same file. Thestruct comedi_file
allocated bycomedi_open()
is freed by the.release()
handlercomedi_close()
(which I ought to rename tocomedi_release
sometime!).