我有linux内核模块,它通过设备文件从用户空间应用程序获取一些信息并返回其他一些数据。
int *g_GlobalVariable;
static ssize_t dev_write(struct file* file, const char __user* buffer, size_t count, loff_t* pos)
{
int i;
int some_size = 10000;
char dev_buffer[64];
copy_from_user(dev_buffer, buffer, count);
g_GlobalVariable = kmalloc(kmalloc(some_size * sizeof(int), GFP_KERNEL);
for(i = 0; i < some_size; i++)
{
g_GlobalVariable[i] = 45; //any info
}
}
当用户空间应用程序从设备文件中读取时,驱动程序执行函数dev_read。
static ssize_t dev_read(struct file* filep, char* buffer, size_t len, loff_t* offset)
{
//do something with g_GlobalVariable
}
我在想,可能的情况是,两个或更多进程使用此驱动程序并且可能发生不好的事情,例如:
1)第一个进程通过设备文件传递数据并生成函数dev_write并填充数组g_GlobalVariable
2)从设备文件中读取第一个进程,调用dev_read并使用g_GlobalVariable
3)第二个进程写入同一个设备文件,g_GlobalVariable包含其他信息。
4)dev_read中的第一个进程获取错误的数据,或读取已经不存在的内存。
我该如何解决这种情况?