2

Is there is a common practice for userspace programs to include ioctl codes used in a kernel module.

mydev.h:

#ifndef MYDEV_H
#define MYDEV_H

#define <linux/ioctl.h>

#define MYDEV_IOC_MAGIC 'C'

#define MYDEV_IOC_FOO   _IO(MYDEV_IOC_MAGIC, 0)
#define MYDEV_IOC_BAR   _IOW(MYDEV_IOC_MAGIC, 1, int)

#endif

I typically put my ioctl codes in a header which I include in my kernel module code. I considered just including this header in my userspace applications, but I realized that the linux/ioctl.h file path may not exist on most systems (e.g. systems with no exported kernel headers).

The solution seems to be to change the include line to: #include <sys/ioctl.h>; but then I couldn't use this header for my kernel module.

Is there a better solution to this problem, or is it common to have two separate but nearly identical header files?

Vilhelm Gray
  • 11,516
  • 10
  • 61
  • 114
  • 3
    If you're concerned about maintenance, you could just automatically generate a userland header from your kernel header when building your module. – Carl Norum Apr 18 '13 at 20:40
  • Is there a way to evaluate a preprocessor macro and print it to a file with GCC's preprocessor? – Vilhelm Gray Apr 19 '13 at 12:37
  • If not, is it usual to write a standalone C program that generates the userland header by passing the defines to a printf; or is there another preferred method? – Vilhelm Gray Apr 19 '13 at 12:57
  • There is the `-E` flag. I'm not sure if that's exactly what you mean. – Carl Norum Apr 19 '13 at 14:12
  • The problem I'm having is that I can't seem to compile a C program which includes `stdio.h` (for generating the file) as well as the Linux kernel headers (for evaluating the ioctl macros). – Vilhelm Gray Apr 22 '13 at 13:56
  • I don't think you should be *including* the kernel header. It should be the *input* to your conversion program. – Carl Norum Apr 22 '13 at 14:11
  • @VilhelmGray In which directory did you add the ioctl header file that needs to be shared between kernel and user program? – dracodormiens Apr 02 '19 at 17:58
  • 1
    @sagargurtu I ended up using in userspace, and in kernelspace. – Vilhelm Gray Apr 03 '19 at 23:34

1 Answers1

6

You could leverage the _KERNEL_ macro.

#ifdef __KERNEL__
#include <linux/ioctl.h>
#else
#include <sys/ioctl.h>
#endif

You may have to abstract the actual ioctl values too, but you get the idea.

Ziffusion
  • 8,779
  • 4
  • 29
  • 57