如何在C/C++中获得Linux系统调用的输出
How do I get the output of a Linux System Call in C/C++?
我在Linux内核中添加了一个简单的helloworld
系统调用。
sys_helloworld
#include <linux/kernel.h>
asmlinkage long sys_helloworld(void)
{
printk("Hello worldn");
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 %ldn", a);
return 0;
}
上述程序成功地在内核日志中打印了Hello world
。
我的问题:
如何在程序中获得sys_hello
(将Hello world
打印到内核日志)的输出?
您应该在系统调用中添加两个参数:要写入的缓冲区及其大小。然后,您可以使用snprintf()
打印您想要的任何字符串。您只需要确保使用正确的系统调用定义宏。由于您需要2个参数,因此此处需要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 worldn");
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 %ldn", a);
printf("buf = %sn", buf);
return 0;
}
请注意,通常使用SYSCALL_DEFINE*
宏来定义系统调用,而不是手动键入asmlinkage long ....
,即使对于没有参数的系统调用(也可以使用SYSCALL_DEFINE0
)。这些宏是在include/sys/syscall.h
中定义的,您应该使用它们。
相关文章:
- 如何使用 C/C++ 和 system() 系统调用以外的其他方法在 Linux 中获取文件功能?
- 如何知道我正在使用的Linux OS是否具有特定的系统调用
- Linux 系统调用 + 交叉编译
- 如何使用C/C 系统调用来获取Linux过程中一个过程的当前大小
- 通过调用 c++ 函数列出 Linux 系统的所有用户名
- 当功能返回时,Linux C 系统()调用崩溃
- 如何使用Linux GetRandom系统调用来在范围内生成一个随机数
- 将 linux 中的 ftime() 系统调用替换为合适的系统调用
- 像 read() 、write() 这样的函数调用在 Linux 中是实际的系统调用吗?
- Linux 读取系统调用不从文件读取
- 在 C++ 中使用 Linux 系统调用以及文件和文件夹管理
- 如何使用linux系统调用编写一个c++程序,该调用提供有关可用内存、已用内存和内核版本的输出
- poll()系统在Linux中调用带有分段错误的核心转储
- 如何在C/C++中获得Linux系统调用的输出
- 从malloc()进行的Windows和Linux本机OS/系统调用是什么
- Linux C++程序通过系统调用启动bash脚本时总是返回-1
- 在Windows上编写C++,但通过Linux模拟器使用Linux系统调用
- Linux-有没有一种方法可以在不分叉新进程的情况下调用系统调用(bash脚本)
- linux中投票系统调用的错误行为
- Linux 系统调用中 C 程序中杂散的“342”杂散“210”杂散“222”时出错