I’ve created a node in /dev by following the tutorial here (chardev.c), I tried to access the device in /dev/chardev I created by using the following code :
#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;
}
successful result:
Device opened
Device read successful : I already told you 7 times Hello world!
w�0 ����
Device closed
However, when memset(receive_buff, 0, sizeof(receive_buff)); is uncommented, I get the following:
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
Question: How does the additional memset() causes the open() to fail ?
opentakes an integer as the second parameter (you’re getting it confused withfopen). Youropenline should be:The reason it works or fails as code is added and removed has to to with the unpredictable value of the address of
"rw", which could happen to be a valid value foropenwhenmemsetis removed.