简体   繁体   中英

how to print debug from both user-space and kernel-space

I am learning embedded system

I need to print debug info on the console from both user-space daemon and kernel-space , I used printf for userspace and printk(KERN_CRIT) for kernel-space.

However, the output is mixed into a mess and out of order. I guess KERN_CRIT is very fast, Is there any clean way to do the job?? Thanks so much

ftrace can resolve your problem.

In linux kernel, you can use "trace_printk" instead of "printk" to log the information, and at the same time in user space you can write the log to the file "trace_marker".

For kernel space:

#include/linux/kernel.h
...
trace_printk("Hello, kernel trace printk  !\n"); 
...

For user space

...
trace_fd = open("trace_marker", WR_ONLY);
void trace_write(const char *fmt, ...)
{
    va_list ap;
    char buf[256];
    int n;

    if (trace_fd < 0)
        return;
    va_start(ap, fmt);
    n = vsnprintf(buf, 256, fmt, ap);
    va_end(ap);
    write(trace_fd, buf, n);
}
...
trace_write("Hello, trace in user space \n");
...

You can find detail information about ftrace in the linux kernel souce code, the path is Documentation/trace/ftrace.txt.

And there are some introduce about ftraces, please focus on trace_printk and trace marker. Debugging the kernel using Ftrace - part 1 Debugging the kernel using Ftrace - part 2

This seems like a problem of synchronising between user and kernel space. Two solutions come to mind.

First, create a debugfs or sysfs interface which holds just one value representing a binary semaphore. Before printing, user program and kernel each will first "down" the value in debugfs or sysfs file. After printing it will "up" it. This can be achieved via wrapper function or macro.

Second, create a debugfs interface. Kernel will always send its logs to that interface rather than printk them. A user space daemon can constantly check that debugfs file. The user program wanting to print will also send its logs to the user space daemon. The daemon can use appropriate synchronisation mechanism like mutex, to ensure that logs never overlap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM