一、格式
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <unistd.h>
#include <sys/syscall.h> /* For SYS_xxx definitions */
int syscall(int number, ...);
二、功能与特点
- syscall()是一个小的库函数,它调用系统调用,该系统调用的汇编语言接口具有指定的带指定参数的数字
- 例如:当调用C库中没有包装函数的系统调用时,使用syscall()非常有用。(如有一个函数gettid()可以得到线程的真正PID,但glibc并没有实现该函数,只能通过Linux的系统调用syscall来获取)
-
syscall()在进行系统调用之前保存CPU寄存器,从系统调用返回时恢复寄存器,如果发生错误,将系统调用返回的任何错误代码存储在errno
三、返回值
- 返回值由正在调用的系统调用定义。一般来说,0返回值表示成功。返回值-1表示错误,错误代码存储在errno中
四、演示案例
- 如有一个函数gettid()可以得到线程的真正PID,但glibc并没有实现该函数,只能通过Linux的系统调用syscall来获取
- SYS_gettid常量就可以得到进程的真是PID
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
pid_t tid;
tid = syscall(SYS_gettid);
printf("tid:%d\n",tid);
tid = syscall(SYS_tgkill, getpid(), tid, SIGHUP);
printf("tid:%d\n",tid);
}