通过shell(cat)或程序(fread)读取proc文件之间的差异
我有一个内核模块在proc fs中创建一个条目,还有一个用户空间程序读取该文件。 我的proc read函数如下所示:通过shell(cat)或程序(fread)读取proc文件之间的差异,c,linux,callback,proc,C,Linux,Callback,Proc,我有一个内核模块在proc fs中创建一个条目,还有一个用户空间程序读取该文件。 我的proc read函数如下所示: typedef struct { int integer; unsigned long ulong; char string[100]; float floatt; bool booll; u16 crc; } struktur; static int round = 0, len = 0, temp = 0, err; struktur *pde_d
typedef struct {
int integer;
unsigned long ulong;
char string[100];
float floatt;
bool booll;
u16 crc;
} struktur;
static int round = 0, len = 0, temp = 0, err;
struktur *pde_data_p;
int proc_read(struct file *filp, char *buf, size_t count, loff_t *offp) {
int i;
unsigned char *crcbuf;
struktur struct_buf;
pde_data_p = PDE_DATA(file_inode(filp));
crcbuf = (unsigned char*)pde_data_p;
memcpy(&struct_buf, pde_data_p, sizeof(struktur));
if (pde_data_p == NULL) {
printk(KERN_ERR "pde->data == NULL\n");
round = 0;
return 0;
}
if (round == 0)
temp = sizeof(struktur);
if (count > temp)
count = temp;
struct_buf.crc = crc16(struct_buf.crc, crcbuf, sizeof(struktur)-sizeof(unsigned short));
err = copy_to_user(buf, pde_data_p, count);
//if (err == 0) { // copy_to_user finished
round = 0;
temp = 0; // taking this line out makes it work in the prog but not with my cat
return temp;
//} else { // copy_to_user failed -> return number of bytes that have not been copied
//temp = err;
//round++;
//return temp;
//}
}
我的程序代码是:
正如您所看到的,我的proc read函数返回读取的字节数,而不是零。
这样,我的程序工作正常,但当我尝试通过cat/proc/sen/entry读取时,它永远不会结束,因为它永远不会返回0。
当我更改代码并在将_复制到_用户完成后返回0时,通过cat读取工作正常,但我的程序似乎读取随机内存。当我返回复制字节数的一半时,用户空间程序读取的数据只有一半是正确的。proc\u read函数必须返回的内容取决于在*offp中移交的位置。如果只需要对给定的用户空间程序代码和cat工作,而不需要对struktur进行部分读取,则只需
if (*offp) return 0; // no more data to return
else *offp = sizeof (struktur); // file position after data returned
-此声明放在复制给用户之前。评论不用于扩展讨论;这段对话已经结束。
if (*offp) return 0; // no more data to return
else *offp = sizeof (struktur); // file position after data returned