我需要一个全局变量,它能够设置其读写权限。
我正在寻找一种在运行时更改全局变量权限的方法。
有没有Linux系统调用支持这个?
例如
int GLOBAL_STATE = 123;
void process_state(){
//only in this function can the GLOBAL_STATE be modified.
//So that I can maintain the value of GLOBAL_STATE
//The permission of GLOBAL_STATE must change to read-write.
...
}
void foo(){
//this function may cause an illegal pointer operator,
//so GLOBAL_STATE may be modified. That is why the permission of
//GLOBAL_STATE must be change to read-only.
}
最佳答案
您的问题展示了全局变量通常为 ill-advised 的几个原因之一。 。通用(即非特定于操作系统)解决方案是使数组静态并隐藏在具有公共(public)访问函数的翻译单元(即非全局)中,然后可以有条件地提供写访问和边界检查。
例如:
Array.c
<小时/>#include <stdbool.h>
static int array[100] ;
static bool protected = false ;
int read_array( unsigned index )
{
return array[index] ;
}
void protect_array()
{
protected = true ;
}
void unprotect_array()
{
protected = false ;
}
void write_array( unsigned index, int value )
{
if( !protected && index < sizeof(array) )
{
array[index] = value ;
}
}
size_t sizeof_array()
{
return sizeof(array) ;
}
size_t lengthof_array()
{
return sizeof(array) / sizeof(*array) ;
}
<小时/>
这提供了读/写访问的全局控制(即在任何时候数组都是 R/W 或 R/O。您可能希望同时向某些用户提供读/写访问权限,并为某些用户提供只读访问权限)其他。这可以通过以下方式实现:
Array.c
<小时/>static int array[100] ;
int* get_array_rw()
{
return array ;
}
const int* get_array_ro()
{
return array ;
}
size_t sizeof_array()
{
return sizeof(array) ;
}
size_t lengthof_array()
{
return sizeof(array) / sizeof(*array) ;
}
<小时/>
此方法将在编译时通过只读指针捕获写入访问尝试。然而,它仍然存在与全局变量相关的大部分问题。
一种不太通用的操作系统特定方法是对数组使用内存映射文件,并使用内存映射文件的访问控制来强加只读或读写语义:
size_t array_len = 100 ;
int fd = open( "arrayfile", O_RDONLY, 0);
if( fd >= 0 )
{
int* array = mmap( NULL, array_len * sizeof(int), PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd, 0);
// Now array points to read only memory
// accessible through normal pointer and array index operations.
}
另一种方法(但不在您的问题范围内)是使用 C++ 并将数组包装在类中,并使用 [] 的运算符重载来访问数组。此方法与第一个建议相同,但在语法上允许像第二个和第三个一样进行类似数组的访问。
关于c - Linux C程序中如何设置全局变量在某个函数中只读,而在其他函数中可读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37627058/