jos*_*osh 5 c linux system-calls
让我们以gettid系统调用为例:
http ://man7.org/linux/man-pages/man2/gettid.2.html
我知道gettidlibc 中没有实现,我需要直接进行系统调用才能使用它(syscall(SYS_gettid))。我自己用这个 C 代码验证了这一点:
#include <stdio.h>
#include <sys/types.h>
int main(){
pid_t a = gettid();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它不链接并在编译时给出此警告:warning: implicit declaration of function 'gettid'; did you mean 'getline'。
现在我的问题是,为什么 Linux 文档记录它就好像这个函数确实存在一样?
SYNOPSIS
#include <sys/types.h>
pid_t gettid(void);
Run Code Online (Sandbox Code Playgroud)
他们没有如何进行直接系统调用的示例,而是有上述不存在且无法使用的代码片段。我有什么遗漏的吗?
系统调用在 GNU C 库(2.30 之前)中没有包装器,这只是函数如果有包装器的原型。
正如手册页中所述:
注意
Glibc 不提供此系统调用的包装器;使用 syscall(2) 调用它。
这是包装器的示例gettid:
#define _GNU_SOURCE
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
pid_t gettid(void)
{
pid_t tid = (pid_t)syscall(SYS_gettid);
return tid;
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这与手册页中描述的原型相同。手册页中的原型仅供参考,因此如果您(或 libc 开发人员)选择,可以围绕系统调用创建一个包装器。
如果您刚刚开始学习 C,我建议您停止尝试理解 C 库中的系统调用及其包装器,直到您对该语言有了更多的经验。那么差异就会很明显。
| 归档时间: |
|
| 查看次数: |
708 次 |
| 最近记录: |