下面的代码是linux kernel的代码,请指出其中的错误,struct student { int id; char name[20]; struct list_head list; }; static LIST_HEAD(student_list); static DEFINE_MUTEX(student_mutex); static int add_student(struct student *stu) { struct student *new_stu = NULL; if (!stu){ printk(KERN_ERR Invalid argument\n"); return -EINVAL; } if (stu->id <= 0){ printk (KERN_ERR "Invalid id\n"); return -EINVAL; } if( !mutex-trylock(&student_mutex)){ printk ( KERN_INFO "Failed to lock mutex\n"); return -EBUSY; } new_stu =kmalloc(sizeof(struct student),GFP_KERNEL); if (!new_stu){ printk(KERN_ERR "Failed to allocate memory\n"); return -ENOMEM; } *new_stu = *stu; list_add_tail(&new_stu->list,&student_list); printk (KERN_INFO "Added student: id=%d,name=%s\n", stu->id, stu->name); mutex_unlock(&student_mutex); return 0; }
时间: 2024-01-16 17:05:02 浏览: 132
代码中有两个错误:
1. 在第10行中,printk函数的字符串缺少一个双引号,应为:"Invalid argument\n"。
2. 在第17行中,mutex-trylock函数应为mutex_trylock函数,即函数名中的"-"应该改为"_"。
正确的代码如下:
```
struct student {
int id;
char name[20];
struct list_head list;
};
static LIST_HEAD(student_list);
static DEFINE_MUTEX(student_mutex);
static int add_student(struct student *stu) {
struct student *new_stu = NULL;
if (!stu) {
printk(KERN_ERR "Invalid argument\n");
return -EINVAL;
}
if (stu->id <= 0) {
printk(KERN_ERR "Invalid id\n");
return -EINVAL;
}
if (!mutex_trylock(&student_mutex)) {
printk(KERN_INFO "Failed to lock mutex\n");
return -EBUSY;
}
new_stu = kmalloc(sizeof(struct student), GFP_KERNEL);
if (!new_stu) {
printk(KERN_ERR "Failed to allocate memory\n");
return -ENOMEM;
}
*new_stu = *stu;
list_add_tail(&new_stu->list, &student_list);
printk(KERN_INFO "Added student: id=%d,name=%s\n", stu->id, stu->name);
mutex_unlock(&student_mutex);
return 0;
}
```
阅读全文