1

I want to use printk function in my userspace code, but I don't want to write kernel module. Is it any possibility to do that?

I tried use linux/kernel.h header and linux/module.h but it doesn't work

printk("<1>some text");
Cliff
  • 140
  • 1
  • 8
user3272
  • 103
  • 1
  • 9
  • 2
    Why do you want to do this? Use printf. – tkausl Jul 22 '19 at 11:15
  • I want write to dmesg so – user3272 Jul 22 '19 at 11:18
  • 5
    If you want to write to system logs from a user-mode program, the usual way to do it is to call [`syslog`](https://linux.die.net/man/3/syslog). – Steve Summit Jul 22 '19 at 11:21
  • Because you don´t compile your code with a reference to your current kernel sources. The standard GCC doesn´t include the sources for kernel modules. – Kampi Jul 22 '19 at 11:38
  • 1
    You can write to the dmesg buffer by writing to `/dev/kmsg`. – Ian Abbott Jul 22 '19 at 14:01
  • Unfortunately, it doesn't work :/ I open file with success but I can't write to it – user3272 Jul 22 '19 at 14:05
  • Assuming you managed to open `/dev/kmsg` as writable, do you get an error when you write to it? Or does the written message simply not appear in the `dmesg` output? There is a sysctl parameter `kernel.printk_devkmsg` to control whether messages written will actually appear. It defaults to "ratelimit" but can be set to "off" or "on". When set to "off" messages from the user will be ignored. When set to "ratelimit" messages from the user will be rate-limited. Also, you may need to terminate your messages with a newline `\n`. – Ian Abbott Jul 23 '19 at 13:25
  • @user3272: dmesg and the kernel log is reserved exclusively for the kernel and kernel related userspace helpers. **It is not meant for _nilly willy_ arbitrary programs!** *Use syslog for that!* – datenwolf Jul 25 '19 at 13:08

2 Answers2

4

Simple Answer is No, You can't use printk in userspace code by any means. printk is designed for kernel programmers. If your intention is to write to syslog -> dmesg, then use syslog() ; It comes in handy!!

Syslog ManPage

Try This:

#include <stdio.h>
#include <unistd.h>
#include <syslog.h>

int main(void) {

 openlog("slog", LOG_PID|LOG_CONS, LOG_USER);
 syslog(LOG_EMERG, "Hello from my code ");
 closelog();

 return 0;
}

To Configure syslog for file redirection:

http://www.softpanorama.org/Logs/syslog.shtml

http://linux.die.net/man/5/syslog.conf

Community
  • 1
  • 1
Cliff
  • 140
  • 1
  • 8
0

Using of kernel headers in userspace makes behavior or program unpredictable. One of reasons is the memory where kernel is located is not accessible from userspace directly.

Here you can find some information about these cases:

Pirate
  • 97
  • 8