我已经按照教程here (chardev.c)在/dev
中创建了一个节点,我尝试使用以下代码访问/dev/chardev
中创建的设备:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h> //perror(), errno
#include <string.h>
#define RSIZE 50
int main()
{
int fd,err_save;
char receive_buff[RSIZE];
//open device and check for error msg
fd = open("/dev/chardev", "rw");
err_save = errno;
if (fd < 0)
{
perror("open perror");
printf("error opening device, fd = %d, err_save = %d \n", fd,err_save);
}
else
{printf("Device opened\n");}
//read device and check for error msg
//memset(receive_buff, 0, sizeof(receive_buff)); //<--- strange
read(fd, receive_buff, RSIZE);
err_save = errno;
if (fd < 0)
{
perror("read perror");
printf("error reading device, fd = %d, err_save = %d \n", fd,err_save);
}
else
{
printf("Device read successful : %s\n",receive_buff);}
//close device and check for error msg
fd = close(fd);
err_save = errno;
if (fd < 0)
{
perror("close perror");
printf("error closing device, fd = %d, err_save = %d \n", fd,err_save);
}
else
{printf("Device closed\n");}
return 0;
}
成功结果:
Device opened
Device read successful : I already told you 7 times Hello world!
w�0 ����
Device closed
但是,当
memset(receive_buff, 0, sizeof(receive_buff));
未注释时,我得到以下结果:open perror: File exists
error opening device, fd = -1, err_save = 17
read perror: Bad file descriptor
error reading device, fd = -1, err_save = 9
close perror: Bad file descriptor
error closing device, fd = -1, err_save = 9
问题:附加的
memset()
如何导致open()
失败? 最佳答案
open
将整数作为第二个参数(您会将其与fopen
混淆)。您的open
行应该是:
fd = open("/dev/chardev", O_RDWR);
当代码被添加和删除时,它工作或失败的原因必须与地址
"rw"
的不可预测值有关,当open
被删除时,该值可能恰好是memset
的有效值。关于c - 额外的memset()导致系统调用open()失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7328602/