How to get Linux system call output in C / C ++?

I added a simple helloworld system call to my Linux kernel.

sys_helloworld

 #include <linux/kernel.h> asmlinkage long sys_helloworld(void) { printk("Hello world\n"); return 0; } 

It just prints Hello world for the kernel log.

I called the sys_helloworld system call as follows:

 #include <stdio.h> #include <linux/kernel.h> #include <sys/syscall.h> #include <unistd.h> int main() { long int a = syscall(314); // 314 is the line number of sys_helloworld in syscall table printf("System call sys_helloworld returned %ld\n", a); return 0; } 

The above program successfully prints Hello world in the kernel log.

My question is:

How to get sys_hello output (which prints Hello world to the kernel log) in my program?

+1
c ++ c linux linux-kernel system-calls
source share
1 answer

You must add two arguments to your syscall: the buffer for writing and its size. Then you can use snprintf() to print any line you want. You just need to make sure that you are using the correct syscall definition macro. Since you need 2 arguments, we need SYSCALL_DEFINE2 here:

 #include <linux/kernel.h> /* For snprintf() */ #include <sys/syscall.h> /* For SYSCALL_DEFINE* macros */ SYSCALL_DEFINE2(sys_helloworld, char *, buff, size_t, buff_sz) { snprintf(buff, buff_sz, "Hello world\n"); return 0; } 

For completeness and depending on the context, you can change the return value to something that lets you know if the string has been truncated or not.

Custom code can call it like this:

 #include <stdio.h> #include <linux/kernel.h> #include <sys/syscall.h> #include <unistd.h> int main() { char buf[32]; long int a = syscall(314, buf, sizeof(buf)); printf("System call sys_helloworld returned %ld\n", a); printf("buf = %s\n", buf); return 0; } 

Note that it is usually better to use the SYSCALL_DEFINE* macros to define your syscall, instead of manually entering the text asmlinkage long .... , even for syscall with no arguments (you would use SYSCALL_DEFINE0 ). These macros are defined in include/sys/syscall.h and you should use them.

+3
source share

All Articles