如何获得C / C ++中的Linux系统调用的输出? [英] How do I get the output of a Linux System Call in C/C++?

查看:495
本文介绍了如何获得C / C ++中的Linux系统调用的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的Linux内核添加了一个简单的 helloworld 系统调用。

I've 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;
}

只是输出 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 在内核日志中。

Above program successfully prints Hello world in kernel log.

我的问题:

在我的程序中输出 sys_hello (它在内核日志中输出 Hello world b $ b

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

推荐答案

您应该为系统调用添加两个参数:要写入的缓冲区及其大小。然后,您可以使用 snprintf()打印所需的任何字符串。你只需要确保使用正确的系统调用定义宏。由于您将需要2个参数,因此我们需要 SYSCALL_DEFINE2

You should add two arguments to your syscall: a buffer to write to, and its size. Then you can use snprintf() to print whatever string you want. You just have to make sure to use the right syscall definition macro. Since you will want 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 might want to change the return value to something that allows you to know whether the string was truncated or not.

用户代码可以这样调用:

User code could 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;
}

请注意,使用 SYSCALL_DEFINE * 宏定义您的系统调用,而不是手动输入 asmlinkage long .... ,即使对于没有参数的系统调用使用 SYSCALL_DEFINE0 )。这些宏定义在 include / sys / syscall.h 中,你应该使用它们。

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

这篇关于如何获得C / C ++中的Linux系统调用的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆