linux系统调用的三种方法

时间:2022-11-27 23:01:44

通过glibc提供的库函数

[23:02:14] gcc chmodtest.c
[23:02:17] ls -l kali //记得先创建这个文件
-rwxrwxrwx. 1 root root 0 May 10 22:56 kali
[23:02:25] ./a.out
chmod succeed
[23:02:29] ls -l kali
-rw-rw-rw-. 1 root root 0 May 10 22:56 kali
[23:02:34] cat chmodtest.c
#include<stdio.h>
int main()
{
int rc=chmod("./kali",0666); //这个必须是4个数字,我用三个数,发现修改的权限对不上
if(rc==-1)
{
perror("chmod fail\n"); //这个是用来打印错误的
}
else
printf("chmod succeed\n");
return 0;
}
[23:02:46]

通过syscall直接调用

[23:10:58] gcc chmodtest1.c
[23:11:01] ls -l kali
-rw-rw-rw-. 1 root root 0 May 10 22:56 kali
[23:11:06] ./a.out
chmod succeed
[23:11:09] ls -l kali
-rwxrwxrwx. 1 root root 0 May 10 22:56 kali
[23:11:13] cat chmodtest1.c
#include<stdio.h>
#include<unistd.h>
#include<sys/syscall.h>
int main()
{
int rc=syscall(SYS_chmod,"./kali",0777);//syscall在头文件unistd.h中,SYS_chmod在头文件syscall.h中
if(rc==-1)
{
perror("chmod fail\n");
}
else
printf("chmod succeed\n");
return 0;
}
[23:11:18]

通过 int 指令陷入(还没有理解是什么意思)

#include <stdio.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <errno.h> int main()
{
long rc;
char *file_name = "/etc/passwd";
unsigned short mode = 0444; asm(
"int $0x80"
: "=a" (rc)
: "0" (SYS_chmod), "b" ((long)file_name), "c" ((long)mode)
); if ((unsigned long)rc >= (unsigned long)-132) {
errno = -rc;
rc = -1;
} if (rc == -1)
fprintf(stderr, "chmode failed, errno = %d\n", errno);
else
printf("success!\n"); return 0;
}