set_bit
是一個 Linux 內核函數,用于在給定的位圖中設置指定位
unsigned int
)作為位圖,其中每個位表示一個特定的權限。#define PERM_READ 0
#define PERM_WRITE 1
#define PERM_EXECUTE 2
unsigned int permissions;
set_bit
函數。#include<linux/bitops.h>
void set_permission(unsigned int *permissions, int permission) {
set_bit(permission, permissions);
}
clear_bit
函數。void clear_permission(unsigned int *permissions, int permission) {
clear_bit(permission, permissions);
}
test_bit
函數。int check_permission(unsigned int *permissions, int permission) {
return test_bit(permission, permissions);
}
現在你可以使用這些函數來實現自定義權限控制。例如:
int main() {
// 初始化權限位圖
permissions = 0;
// 設置讀、寫和執行權限
set_permission(&permissions, PERM_READ);
set_permission(&permissions, PERM_WRITE);
set_permission(&permissions, PERM_EXECUTE);
// 檢查權限
if (check_permission(&permissions, PERM_READ)) {
printf("Read permission granted.\n");
}
if (check_permission(&permissions, PERM_WRITE)) {
printf("Write permission granted.\n");
}
if (check_permission(&permissions, PERM_EXECUTE)) {
printf("Execute permission granted.\n");
}
// 清除寫權限
clear_permission(&permissions, PERM_WRITE);
// 再次檢查權限
if (!check_permission(&permissions, PERM_WRITE)) {
printf("Write permission revoked.\n");
}
return 0;
}
這個示例將輸出:
Read permission granted.
Write permission granted.
Execute permission granted.
Write permission revoked.
請注意,這個示例僅適用于簡單的權限管理。在實際應用中,你可能需要根據具體需求進行更復雜的權限管理。