Reputation: 1323
I'm writing a code and im using libudev.h so far i can i can detect devices and open them and put the fd's of the opened devices in devlist for reading and writing of data. My problem is that when i unplugged the device i get a segmentation error.
if (FD_ISSET(fd, &fds))
{
dev = udev_monitor_receive_device(mon);
if (dev)
{
if(strcmp(udev_device_get_action(dev),"add")==0)
{
if(strcmp(udev_device_get_devnode(dev), "/dev/ttyUSB0")==0)
{
fd1 = open(udev_device_get_devnode(dev), O_RDWR | O_NONBLOCK);
if(fd1<0)
{
printf("Can't open Device\n");
exit(0);
}
}
printf("Device plugged\n");
printf(" Node: %s\n", udev_device_get_devnode(dev));
printf(" Action: %s\n", udev_device_get_action(dev));
printf("device opened\n");
int opt =1;
ioctl(fd1, FIONBIO,(char *) &opt);
for(loop=0; loop<MAXDEV; loop++)
if(devlist[loop] == 0)
{
devlist[loop] = fd1;
fd1 = -1;
}
}
else {
printf("Device unplugged\n");
printf(" Node: %s\n", udev_device_get_devnode(dev));
printf(" Action: %s\n", udev_device_get_action(dev));
FD_CLR(devlist[loop],&fds);
close(devlist[loop]);
devlist[loop] = -1;
}
udev_device_unref(dev);
}
Once i get deviced open i can read to its fd and there's no problem with it but when i unplugged the device i get error.
this is the part where i'm having trouble.
printf("Device unplugged\n");
printf(" Node: %s\n", udev_device_get_devnode(dev));
printf(" Action: %s\n", udev_device_get_action(dev));
FD_CLR(devlist[loop],&fds);
close(devlist[loop]);
devlist[loop] = -1;
Thanks..
Upvotes: 1
Views: 1386
Reputation: 8511
Accessing a USB serial adapter after it's been unplugged doesn't cause a segfault for me--I tested this pretty heavily for my work a while back.
I notice for one thing that you don't seem to have initialized "loop" to the element of "devlist" that corresponds to unplugged device. That might happen to work if you haven't returned from the function between the plug and unplug events and you unplug the same device as you last plugged in. But that's my bet for where you're segfaulting.
The other candidate I'd suspect is your code for reading or writing the device. The read and write syscalls will return -1 after the device is unplugged, and if you aren't checking for that error or your error handling code has a bug, that could be your problem too.
In general, I'd recommend running your program under gdb and getting a stack trace when it crashes. That will tell you which line number the error occurred on.
Upvotes: 2