我正在尝试在我的dmesg输出中写入一些自定义消息。 我试过了:
logger "Hello"
但是这不起作用。 它退出没有错误,但没有“你好”出现在输出:
dmesg
我正在使用Fedora 9,似乎没有运行syslogd / klogd守护进程。 但是,我的所有内核消息都成功写入了dmesg缓冲区。
任何想法?
dmesg
显示内核缓冲区中的内容,而logger
是针对syslogd
。 我想如果你想打印内核缓冲区的东西,你需要创build一个使用printk()
内核函数的驱动程序。 如果你只是想在/var/log/messages
,然后用“正常”的设置,我认为你已经做了logger
已经很好。
带有printk()
的驱动程序最基本的例子是:
hello.c中:
#include <linux/module.h> #include <linux/kernel.h> int init_module(void) { printk(KERN_INFO "Hello world\n"); return 0; } void cleanup_module(void) { printk(KERN_INFO "Goodbye world\n"); }
Makefile文件:
obj-m += hello.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
然后:
$ make $ sudo insmod hello.ko $ dmesg | tail -n1 [7089996.746366] Hello world
http://tldp.org/LDP/lkmpg/2.6/html/lkmpg.html#AEN121更多…
您可以以root身份写入/dev/kmsg
以打印到内核消息缓冲区:
fixnum:~# echo Some message > /dev/kmsg fixnum:~# dmesg | tail -n1 [28078118.692242] Some message
我已经在我的服务器和embedded式Linux设备上testing了这个function,它在两者上都能正常工作,所以我只是假设它在任何地方都能正常工作。
基于上面的凯尔模块:
#include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/proc_fs.h> #include <asm/uaccess.h> static int pk_write(struct file *file, const char *buffer, unsigned long count, void *data) { char string[256]; count = count < 255 ? count : 255; if(copy_from_user(string, buffer, count)) return -EFAULT; string[count] = '\0'; printk(string); return count; } static int __init printk_init(void) { struct proc_dir_entry *pk_file; pk_file = create_proc_entry("printk", 0222, NULL); if(pk_file == NULL) return -ENOMEM; pk_file->write_proc = pk_write; pk_file->owner = THIS_MODULE; return 0; } static void __exit printk_cleanup(void) { remove_proc_entry("printk", NULL); } module_init(printk_init); module_exit(printk_cleanup); MODULE_LICENSE("GPL");
从用户空间执行printk:
echo "Hello" > /proc/printk
@ Calandoa的答案不再适用于Kernel +3.10。 结合他的代码和我在这里find的示例代码。 然后改善代码质量…
代码保存到printk_user.c
#include <linux/module.h> #include <linux/kernel.h> #include <linux/proc_fs.h> #include <asm/uaccess.h> static ssize_t write_proc(struct file *filep, const char *buffer, size_t count, loff_t *offsetp) { char string[256]; count = count < 255 ? count : 255; if(copy_from_user(string, buffer, count) != 0) { return -EFAULT; } string[count] = '\0'; printk(string); return count; } static const struct file_operations proc_fops = { .owner = THIS_MODULE, .write = write_proc, }; static int proc_init(void) { struct proc_dir_entry *proc_file; proc_file = proc_create("printk_user", 0, NULL, &proc_fops); if(proc_file == NULL) { return -ENOMEM; } return 0; } static void proc_cleanup(void) { remove_proc_entry("printk_user", NULL); } MODULE_LICENSE("GPL"); module_init(proc_init); module_exit(proc_cleanup);
使用这个Makefile
TARGET = printk_user obj-m := $(TARGET).o KERNEL_VERSION=$(shell uname -r) KDIR = /lib/modules/$(KERNEL_VERSION)/build PWD = $(shell pwd) printk: $(MAKE) -C $(KDIR) M=$(PWD) modules clean: $(MAKE) -C $(KDIR) M=$(PWD) clean
基于凯尔的答案, 这是一个快速教程,展示如何做到这一点。