gpt4 book ai didi

c - 调用 open 时如何调用 sys_open 而不是 sys_openat

转载 作者:行者123 更新时间:2023-12-04 19:40:35 24 4
gpt4 key购买 nike

我写了一个代码来生成系统调用

void open_test(int fd, const char *filepath) {
if (fd == -1) {
printf("Open \"%s\" Failed!\n", filepath);
} else {
printf("Successfully Open \"%s\"!\n", filepath);
write(fd, "successfully open!", sizeof("successfully open!") - 1);
close(fd);
}
fflush(stdout);
}

int main(int argc, char const *argv[]) {
const char fp1[] = "whatever.txt", fp2[] = "./not-exist.txt";
int fd1 = open(fp1, O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU);
int fd2 = open(fp2, O_WRONLY | O_TRUNC, S_IRWXU);
open_test(fd1, fp1);
open_test(fd2, fp2);
return 0;
}
和另一个程序(细节省略)来捕捉系统调用,但后来我发现所有 open()原来是调用 sys_openat 而不是 sys_open。
以下文本是程序的输出:
Detect system call open, %rax is 257, Addr is 0x00007fefef78aec8, Pathname is /etc/ld.so.cache
Detect system call open, %rax is 257, Addr is 0x00007fefef78aec8, Pathname is /etc/ld.so.cache
Detect system call open, %rax is 257, Addr is 0x00007fefef993dd0, Pathname is /lib/x86_64-linux-gnu/libc.so.6
Detect system call open, %rax is 257, Addr is 0x00007fefef993dd0, Pathname is /lib/x86_64-linux-gnu/libc.so.6
Detect system call open, %rax is 257, Addr is 0x00007fffd44e38e3, Pathname is whatever.txt
Detect system call open, %rax is 257, Addr is 0x00007fffd44e38e3, Pathname is whatever.txt
Detect system call open, %rax is 257, Addr is 0x00007fffd44e38f0, Pathname is ./not-exist.txt
Detect system call open, %rax is 257, Addr is 0x00007fffd44e38f0, Pathname is ./not-exist.txt
Successfully Open "whatever.txt"!
Open "./not-exist.txt" Failed!
这里 rax=257 表示调用了 sys_openat(对于 sys_open,rax=2)

最佳答案

您调用syscall(2)包装:syscall(SYS_open, ...) :

#define _GNU_SOURCE
#include <unistd.h>
#include <fcntl.h>
#include <err.h>
#include <sys/syscall.h>

int main(void){
char *path = "whatever.txt";
int fd = syscall(SYS_open, path, O_RDONLY, 0);
if(fd == -1) err(1, "SYS_open %s", path);
}
但是为什么要打扰呢? SYS_openat现在是规范的系统调用, open(2)只是一个 API,而 SYS_open系统调用条目仅出于向后二进制兼容性而保留。
在较新的架构上,可能没有实际的 SYS_open系统调用。

关于c - 调用 open 时如何调用 sys_open 而不是 sys_openat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64407019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com