简体   繁体   中英

How do I make syscalls from my C program

How do I make system calls from my C program. For example, how do I call the following function? What headers would I have to include?

asmlinkage long sys_exit(int error_code);

You would normally call C library wrappers for the system calls (for example open() and read() are just wrappers). Wrappers are more friendly.

As an alternative to do the work yourself in assembly, you can try the syscall(2) function from glibc. This function makes a system call without a wrapper, and is specially useful when invoking a system call that has no wrapper function. In this manner you just need to provide symbolic constants for system call numbers, and also i think is more portable than coding the system call in assembler instructions.

Example from the doc:

#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
int
main(int argc, char *argv[])
{
    pid_t tid;
    tid = syscall(SYS_gettid);
    tid = syscall(SYS_tgkill, getpid(), tid);
}
asm volatile(
              "xorq %%rdi, %%rdi;"  /* return value */
              "movq $60, %%rax;"    /* syscall id (/asm/unistd_64.h   */
              "syscall;" 
              ::: "rdi", "rax"
            );

You can't call it from pure C but you need to invoke it from assembly as would any wrapper like glibc . Another way is using int 80h , but that's rather outdated.

In rdi you put error_code ( 0 in this case) while in rax the number which identifies the system call, available in /usr/include/asm/unistd.h that will in turn point you to the 32 or 64 bit version.

#define __NR_exit 60

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM