linux的系统调用api都在那些头文件里?注意是系统调用而不是c库函数!
这个我再多说几句,Linux和Windows不太一样,通常来说,Linux只是一个内核,相当于 ntkernel。在Windows上,用户界面API是 user32.dll 提供的,而Linux实际上没有唯一的用户界面,可以根据发行版的不同搭配 Gome、GTK、KDE,这些不同的对应不同的库。所以自然就没有什么统一 API 之说了。
晚晴 李商隐 深居俯夹城,春去夏犹清。天意怜幽草,人间重晚晴。 并添高阁迥,微注小窗明。越鸟巢干后,归飞体更轻。
Linux系统调用API定义在各个头文件中,以下是常用的头文件和对应的系统调用API:
其中,常用的系统调用API包括:
open
: 打开文件creat
: 创建文件lseek
: 设置文件指针位置close
: 关闭文件access
: 判断文件权限opendir
: 打开目录readdir
: 读取目录closedir
: 关闭目录下面以问题中的例子来展示具体的代码实现。
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("./a.out filename\n");
return -1;
}
int fd = open(argv[1], O_RDONLY);
if (fd == -1) { // 处理打开文件失败的情况
perror("open"); // 打印错误信息
return -1;
}
off_t ret = lseek(fd, 0, SEEK_END); // 使用off_t类型保存文件大小
if (ret == -1) { // 处理lseek失败的情况
perror("lseek");
close(fd);
return -1;
}
printf("file size is: %ld\n", ret); // 使用%ld打印off_t类型的值
close(fd);
return 0;
}
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("./a.out filename\n");
return -1;
}
if (access(argv[1], R_OK) == 0) {
printf("%s read is ok!\n", argv[1]);
}
if (access(argv[1], W_OK) == 0) {
printf("%s write is ok!\n", argv[1]);
}
if (access(argv[1], X_OK) == 0) {
printf("%s execute is ok!\n", argv[1]);
}
if (access(argv[1], F_OK) == 0) {
printf("%s file exists!\n", argv[1]);
}
return 0;
}
#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int count = 0;
int dirCount(char *dirname) {
printf("%s\n", dirname); // 打印路径
DIR *dirp = opendir(dirname); // 打开目录
if (dirp == NULL) {
perror("opendir err: ");
return -1;
}
struct dirent *dentp = NULL;
while ((dentp = readdir(dirp)) != NULL) { // 循环读取目录项
if (dentp->d_type == DT_DIR) { // 判断是否是目录
if (strcmp(".", dentp->d_name) == 0 || strcmp("..", dentp->d_name) == 0) {
continue; // 遇到'.'和'..'跳过
}
char newdirname[257] = {0};
sprintf(newdirname, "%s/%s", dirname, dentp->d_name); // 拼接新路径
dirCount(newdirname); // 递归进入子目录
}
if (dentp->d_type == DT_REG) { // 判断是否是普通文件
++count;
printf("dname : %s\n", dentp->d_name); // 打印文件名
}
}
closedir(dirp); // 关闭目录
return count;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("./a.out dirname\n");
return -1;
}
int fileCount = dirCount(argv[1]);
printf("count = %d\n", fileCount);
return 0;
}
希望以上内容能够帮助到您理解Linux系统调用API和对应的头文件。如果还有其他问题,请随时提问。
Linux系统调用的API函数声明通常存储在 <sys/syscall.h> 头文件中。在这个头文件中,每个系统调用都有一个宏定义来指定它的调用号(syscall number),以及相应的函数原型声明。这个头文件中定义的宏通常以 _NR 开头,后面跟着系统调用的名称,如 __NR_read、__NR_write 等。
但是需要注意的是,直接使用这些系统调用的函数原型和调用号可能会比较繁琐和不方便,因此通常会使用C库中封装好的函数来调用这些系统调用,例如 open()、read()、write() 等,这些C库函数会在内部调用相应的系统调用。所以,尽管你强调不是C库函数,但实际上在开发过程中,直接使用C库函数更加常见和方便。
如果你确实需要直接使用系统调用,可以参考 <sys/syscall.h> 头文件中的宏定义和函数原型来进行操作。不过,了解C库提供的函数通常更加实际和便捷。