低级系统调用

sau*_*405 3 system-programming system-calls

C 为系统调用提供了诸如 write(),read().. 等库函数。如何在不使用 Linux 中的任何库的情况下在 C 中进行系统调用?

Bru*_*ger 5

野心或对纯度的过度渴望会导致您进行在线组装。例如,在 x86_64 系统上,您可以执行如下open(2)系统调用:

#include <sys/syscall.h>
int
linux_open(const char *pathname, unsigned long flags, unsigned long mode)
{
    long ret;
    asm volatile ("syscall" : "=a" (ret) : "a" (__NR_open),
              "D" (pathname), "S" (flags), "d" (mode) :
              "cc", "memory", "rcx",
              "r8", "r9", "r10", "r11" );
    if (ret < 0)
    {
        errno = -ret;
        ret = -1;
    }
    return (int) ret;
}
Run Code Online (Sandbox Code Playgroud)

您也可以查看更易于理解的 libc(如Musl)的来源,以了解系统调用是如何实现的。