我向我的Linux添加了一个简单的helloworld系统调用。
sys_helloworld
#include <linux/kernel.h>
asmlinkage long sys_helloworld(void)
{
printk("Hello world\n");
return 0;
}它只是将Hello world打印到内核日志。
我是这样调用sys_helloworld系统调用的:
#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;
}上面的程序在内核日志中成功地打印了Hello world。
我的问题:
如何在我的程序中获得sys_hello的输出(将Hello world打印到内核日志)?
发布于 2014-11-09 13:18:36
您应该向syscall添加两个参数:一个要写入的缓冲区及其大小。然后您可以使用snprintf()打印任何您想要的字符串。您只需确保使用正确的syscall定义宏即可。因为您需要两个参数,所以这里需要SYSCALL_DEFINE2:
#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;
}为了完整,并根据上下文的不同,您可能希望将返回值更改为允许您知道字符串是否被截断的内容。
用户代码可以这样称呼它:
#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;
}请注意,使用SYSCALL_DEFINE*宏定义syscall通常更好,而不是手动在asmlinkage long ....中键入,即使对于没有参数的syscall也是如此(您可以使用SYSCALL_DEFINE0)。这些宏是在include/sys/syscall.h中定义的,您应该使用它们。
https://stackoverflow.com/questions/26828461
复制相似问题