温馨提示×

linux c++如何调用系统api

小樊
39
2026-09-02 02:49:48
栏目: 编程语言

在 Linux 下用 C/C++ 调用“系统 API”,通常有以下几种层级和做法,从最底层到更上层依次是:


一、直接调用 Linux 系统调用(syscall)

Linux 的“系统 API”最底层就是 系统调用(system call),比如:

  • open / read / write
  • fork / exec
  • socket
  • ioctl

1️⃣ 使用 glibc 封装的函数(最常见)

#include <fcntl.h>
#include <unistd.h>
#include <iostream>

int main() {
    int fd = open("/tmp/test.txt", O_WRONLY | O_CREAT, 0644);
    if (fd < 0) {
        perror("open");
        return 1;
    }
    write(fd, "hello", 5);
    close(fd);
}

✅ 编译:

g++ test.cpp -o test

✅ 这些函数本质上是 glibc 对系统调用的封装


2️⃣ 直接使用 syscall()(不推荐但可用)

#include <sys/syscall.h>
#include <unistd.h>
#include <iostream>

int main() {
    long pid = syscall(SYS_getpid);
    std::cout << "pid=" << pid << std::endl;
}

⚠️ 可移植性差,一般只在极端情况下使用


二、调用 C 标准库(libc / glibc)

Linux 程序默认链接 glibc:

#include <cstdio>
#include <cstdlib>

int main() {
    system("ls -l");
    printf("random: %d\n", rand());
}

三、调用 Linux 特有的 API(如 epoll、inotify)

epoll 示例

#include <sys/epoll.h>
#include <unistd.h>

int epfd = epoll_create1(0);

inotify 示例

#include <sys/inotify.h>
int fd = inotify_init();

这些属于 Linux 特有系统 API


四、调用系统命令(不是 API,但常用)

#include <cstdlib>

system("ifconfig");

或使用 popen 获取输出:

FILE* p = popen("ls", "r");

五、调用动态库中的系统/第三方 API(dlopen)

#include <dlfcn.h>

void* h = dlopen("libm.so.6", RTLD_LAZY);

六、调用内核模块 / ioctl(高级)

#include <sys/ioctl.h>
ioctl(fd, CMD, &arg);

常用于:

  • 驱动
  • 显卡
  • 网络设备

七、常见头文件速查

功能 头文件
文件 <fcntl.h> <unistd.h>
进程 <sys/types.h> <unistd.h>
网络 <sys/socket.h>
线程 <pthread.h>
内存 <sys/mman.h>

八、推荐学习路径

  1. ✅ 先学 文件 / 进程 / 线程
  2. ✅ 再学 socket / epoll
  3. ✅ 最后学 ioctl / 内核模块

如果你有具体想调用的系统 API(比如 epoll、fork、ptrace、netlink、io_uring),可以直接说,我可以给你完整可运行示例

0