基本参考newsmth的Kernel Tech版的那个FAQ就可以,准则如下:
4.2 在内核中可以使用系统调用吗?
a. 可以。内核源代码中就有使用系统调用的例子,如open()、execve()等。
b. 在内核中使用系统调用必须要在源文件中包括以下两行:
#define __KERNEL_SYSCALLS__
#include <linux/unistd.h>
c. 内核中使用系统调用的相关定义可查看文件include/asm/unistd.h。
如果要用的系统调用该文件中没有定义,可以按照其格式自行添加。
d. 如果要在模块中使用系统调用,必须要自己定义errno如:
int errno;
内核在lib/errno.c中定义了errno,但该符号不导出,所以模块编程时需要自己
定义errno,用以存放系统调用出错号。
但是对于我这样的菜菜,还是有点不够详细,自己实践了一下,于是在下边给个实例出来,希望能给和我一样的新手们一些帮助:(展示了调用getpid()和stat())
主要注意那个_syscallX的macro就可以了,这个newsmth的FAQ中没说。
btw:
突然发现自己今天写了3篇blog了,._.Y
同时发现编译内核是CPU密集型操作,而不是I/O密集型,因为编译的时候CPU风扇狂转,嗡嗡的,而硬盘声几乎没变,呵呵。
决定把自己blog的名称改回AAOP了,其意自明~
4.2 在内核中可以使用系统调用吗?
a. 可以。内核源代码中就有使用系统调用的例子,如open()、execve()等。
b. 在内核中使用系统调用必须要在源文件中包括以下两行:
#define __KERNEL_SYSCALLS__
#include <linux/unistd.h>
c. 内核中使用系统调用的相关定义可查看文件include/asm/unistd.h。
如果要用的系统调用该文件中没有定义,可以按照其格式自行添加。
d. 如果要在模块中使用系统调用,必须要自己定义errno如:
int errno;
内核在lib/errno.c中定义了errno,但该符号不导出,所以模块编程时需要自己
定义errno,用以存放系统调用出错号。
但是对于我这样的菜菜,还是有点不够详细,自己实践了一下,于是在下边给个实例出来,希望能给和我一样的新手们一些帮助:(展示了调用getpid()和stat())
#define __KERNEL_SYSCALLS__
#include <linux/unistd.h>
#include <linux/stat.h> // other needed header
int errno // if needed
//
unsigned int getsockcnt(void)
{
_syscall0(int, getpid) //must needed
_syscall2(int, stat, const char *, file_name, struct stat *, buf) //must needed
unsigned int n = 0;
pid_t pid = getpid(); // systemcall
char path[256];
sprintf(path, "/proc/%d/fd", pid);
int i = 0;
for (; i < 1024; i++)
{
sprintf(path, "/proc/%d/fd/%d", pid, i);
struct stat st;
if (stat(path, &st) == 0) // system call
if (S_ISSOCK(st.st_mode))
n++;
}
return n;
}
// call this function
#include <linux/unistd.h>
#include <linux/stat.h> // other needed header
int errno // if needed
//
unsigned int getsockcnt(void)
{
_syscall0(int, getpid) //must needed
_syscall2(int, stat, const char *, file_name, struct stat *, buf) //must needed
unsigned int n = 0;
pid_t pid = getpid(); // systemcall
char path[256];
sprintf(path, "/proc/%d/fd", pid);
int i = 0;
for (; i < 1024; i++)
{
sprintf(path, "/proc/%d/fd/%d", pid, i);
struct stat st;
if (stat(path, &st) == 0) // system call
if (S_ISSOCK(st.st_mode))
n++;
}
return n;
}
// call this function
主要注意那个_syscallX的macro就可以了,这个newsmth的FAQ中没说。
btw:
突然发现自己今天写了3篇blog了,._.Y
同时发现编译内核是CPU密集型操作,而不是I/O密集型,因为编译的时候CPU风扇狂转,嗡嗡的,而硬盘声几乎没变,呵呵。
决定把自己blog的名称改回AAOP了,其意自明~