在 Linux 下用 C/C++ 调用“系统 API”,通常有以下几种层级和做法,从最底层到更上层依次是:
Linux 的“系统 API”最底层就是 系统调用(system call),比如:
open / read / writefork / execsocketioctl#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 对系统调用的封装
syscall()(不推荐但可用)#include <sys/syscall.h>
#include <unistd.h>
#include <iostream>
int main() {
long pid = syscall(SYS_getpid);
std::cout << "pid=" << pid << std::endl;
}
⚠️ 可移植性差,一般只在极端情况下使用
Linux 程序默认链接 glibc:
#include <cstdio>
#include <cstdlib>
int main() {
system("ls -l");
printf("random: %d\n", rand());
}
#include <sys/epoll.h>
#include <unistd.h>
int epfd = epoll_create1(0);
#include <sys/inotify.h>
int fd = inotify_init();
这些属于 Linux 特有系统 API
#include <cstdlib>
system("ifconfig");
或使用 popen 获取输出:
FILE* p = popen("ls", "r");
#include <dlfcn.h>
void* h = dlopen("libm.so.6", RTLD_LAZY);
#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> |
如果你有具体想调用的系统 API(比如 epoll、fork、ptrace、netlink、io_uring),可以直接说,我可以给你完整可运行示例。