使用C中的ioctl()设置不可变标志 [英] Setting Immutable Flag using ioctl() in C

查看:154
本文介绍了使用C中的ioctl()设置不可变标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个脚本来创建一个文件,然后将其设置为不可变的,类似于linux的 chattr + i 命令。 脚本编译(使用gcc),运行文件创建。但文件本身不是不可变的,可以用 rm -f 来删除文件。我试图堆栈跟踪调用 chattr 的地方,并且找到了一个名为 ioctl 的函数。然后,我使用了我可以收集的一些小信息,并提出了我下面的内容。我从 ext2_fs.h 缩小了范围,但它似乎不起作用。我清楚地忽略了一些东西。



以前的更新编译,但是返回-1 在ioctl()函数上。 perror()显示的错误地址

  #include< stdio.h中> 
#include< stdlib.h>
#include< sys / stat.h>
#include< sys / ioctl.h>
#include< linux / fs.h>

int main()
{
FILE * fp;
char铲[16] =我有一把铁锹!;
fp = fopen(/ shovel.txt,w +);
fwrite(shovel,sizeof(铲[0]),sizeof(铲)/ sizeof(铲[0]),fp);
ioctl(fileno(fp),FS_IOC_SETFLAGS,0x00000010);
fclose(fp);






ioctl 需要一个指向的mask,而不是直接指向不变。你必须定义一个int变量,在其中存储掩码( 0x10 ),并将其地址作为 ioctl

另外,我会添加一些提示:


  • 其他程序更改属性用于直接使用低级I / O(打开,关闭...)。另外,该文件通常以 O_RDONLY 打开。

  • 使用 FS_IMMUTABLE_FL 取决于原始常量。

  • 首先获取当前属性掩码( FS_IOC_SETFLAGS ),并用新标志屏蔽它,这样其他设置不会丢失。


I have attempted to make a script that creates a file and then sets it as immutable similar to the chattr +i command for linux. The script compiles (with gcc), runs and the file is created. However the file itself is not immutable and can be removed with a simple rm -f. I have attempted to stacktrace where chattr is called and I found a function called ioctl. I then used what little information I could gather and came up with what I have below. I narrowed it down from ext2_fs.h but it just doesn't seem to work. I've clearly overlooked something.

Updates to previous entry: Compiles but returns -1 on ioctl() function. Bad address shown with perror().

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/fs.h>

int main()
{
    FILE *fp;
    char shovel[16] = "I have a shovel!";
    fp = fopen("/shovel.txt", "w+");
    fwrite(shovel, sizeof(shovel[0]), sizeof(shovel)/sizeof(shovel[0]), fp);
    ioctl(fileno(fp), FS_IOC_SETFLAGS, 0x00000010);
    fclose(fp);
}

Any help appreciated.

解决方案

The main problem is that the ioctl wants a pointer to the mask, not a direct constant. You have to define a int variable, store the mask (0x10) in it and pass its address as third argument of ioctl.

Also, I'd add some hints:

  • other programs to change attributes are used to use low-level I/O directly (open, close...). Also, the file is usually opened with O_RDONLY.
  • Use FS_IMMUTABLE_FL istead the raw constant.
  • Get the current attribute mask first (FS_IOC_SETFLAGS) and mask it with the new flag, so other settings are not lost by the service.

这篇关于使用C中的ioctl()设置不可变标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆