C 无法从用户空间应用程序访问结构数组
在公共标题中,我将结构定义为:C 无法从用户空间应用程序访问结构数组,c,kernel,ioctl,C,Kernel,Ioctl,在公共标题中,我将结构定义为: #define query_arg_t queryForItems typedef struct { char item[50]; char status[10]; } queryForItems; 在内核驱动程序中,我们定义: //初始化 queryForItems queryForItemsArray[] = { { .item = "A", .status = "TRUE" }, { .item = "B", .status =
#define query_arg_t queryForItems
typedef struct {
char item[50];
char status[10];
} queryForItems;
在内核驱动程序中,我们定义:
//初始化
queryForItems queryForItemsArray[] = {
{
.item = "A",
.status = "TRUE"
},
{
.item = "B",
.status = "TRUE"
},
};
在驱动程序中使用ioctl
static long my_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
{
query_arg_t *q;
switch (cmd)
{
case QUERY_GET_VARIABLES:
memcpy(&q, (&queryListForItems), sizeof(queryForItemsArray));
if (copy_to_user((query_arg_t *)arg, &q, sizeof(query_arg_t))) {
return -EACCES;
}
break;
:
在用户应用程序中,我们将get函数定义为:
void get_vars(int fd)
{
query_arg_t *q;
//q.info = kmalloc(sizeof(???), GFP_KERNEL); // may require malloc
if (ioctl(fd, QUERY_GET_VARIABLES, &q) == -1)
{
perror("query_apps ioctl get");
} else {
printf("=====================\n");
printf("option: %s \n", q[1].Item);
printf("=====================\n");
}
}
但是,我无法从用户空间应用程序访问struct数组。[Sakthi Kumar建议的解决方案] 在公共标题中: 添加 司机 在用户应用程序中:
您定义了my_ioctl并调用ioctl为什么?my_ioctl在内核空间中,当fd=openfile_name,调用O_RDWR时,ioctl被映射。@Babbit q需要分配内存。您可以为结构中的元素数定义一个上限吗。我指的是在任何时间点可能达到的最大值。如果可以定义最大值,则始终可以为最大值分配结构,但要有一个变量来指示有效计数。由于指针从用户空间移动到内核空间,我认为这是唯一的方法。我在聊天室看到了你的消息,你能再次加入聊天室吗?
#define MAX_OBJ 50
typedef struct {
int num_items;
queryForItems items[MAX_OBJ];
} query_arg_t;
case QUERY_GET_VARIABLES:
q = kmalloc(sizeof(query_arg_t), GFP_KERNEL);
q->num_items = 3;
memcpy(q->items, queryForItems, sizeof(queryForItems) * q->num_items);
if (copy_to_user((query_arg_t *)arg, q, sizeof(query_arg_t))) {
return -EACCES;
}
break;
query_arg_t *q;
q = malloc(sizeof(query_arg_t));
if (ioctl(fd, QUERY_GET_VARIABLES, q) == -1)
{
perror("query_apps ioctl get");
} else {
printf("=====================\n");
printf("option: %s \n", q->items[i].status);