-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrmusbbdev.c
83 lines (71 loc) · 2.07 KB
/
rmusbbdev.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#define _FILE_OFFSET_BITS 64
// asprintf, basename
#define _GNU_SOURCE
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <libudev.h>
int main(int argc, char **argv)
{
struct stat sb;
struct udev *ucxt;
struct udev_device *blkdev, *usbdev;
char *devname, *syspath;
int fd;
if (argc != 2)
{
fprintf(stderr, "Uso: %s dispositivo\n", basename(argv[0]));
exit(EXIT_FAILURE);
}
if (stat(argv[1], &sb) != 0 || !S_ISBLK(sb.st_mode))
{
fprintf(stderr, "Dispositivo inexistente ou não de bloco.\n");
exit(EXIT_FAILURE);
}
devname = realpath(argv[1], NULL);
if (devname == NULL)
{
perror("realpath");
exit(EXIT_FAILURE);
}
ucxt = udev_new();
blkdev = udev_device_new_from_subsystem_sysname(ucxt, "block", basename(devname));
if (blkdev != NULL)
{
usbdev = udev_device_get_parent_with_subsystem_devtype(blkdev, "usb", "usb_device");
if (usbdev != NULL)
{
// https://github.com/torvalds/linux/commit/253e05724f9230910344357b1142ad8642ff9f5a
if (asprintf(&syspath, "%s/remove", udev_device_get_syspath(usbdev)) > 0)
{
fd = open(syspath, O_WRONLY);
if (fd >= 0)
{
printf("Desconectando porta USB %s... ", udev_device_get_sysname(usbdev));
fflush(stdout);
if (write(fd, "1", 1) == 1)
{
printf("sucesso.\n");
fflush(stdout);
}
else
{
printf("falha.\n");
fflush(stdout);
}
close(fd);
}
free(syspath);
}
// usbdev é desalocado junto com blkdev
}
udev_device_unref(blkdev);
}
free(devname);
udev_unref(ucxt);
return EXIT_SUCCESS;
}