fcntl(int sg_fd, int cmd, long arg). There are several uses for this system call in association with a sg file descriptor. The following pseudo code shows code that is useful for scanning the sg devices, taking care not to be caught in a wait for an O_EXCL lock by another process, and when the appropriate device is found, switching to normal blocked io. A working example of this logic is in the sg_scan utility program.
open("/dev/sg0", O_RDONLY | O_NONBLOCK) /* check device, EBUSY means some other process has O_EXCL lock on it */ /* when the device you want is found then ... */ flags = fcntl(sg_fd, F_GETFL) fcntl(sg_fd, F_SETFL, flags & (~ O_NONBLOCK)) /* since, with simple apps, it is easier to use normal blocked io */
The sg driver supports asynchronous notification. This is a non-blocking mode of operation in which, when the driver receives data back from a device so that a read() can be done, it sends a SIGPOLL (aka SIGIO) signal to the owning process. Here is a code snippet from the sg_poll test program.
sigemptyset(&sig_set) sigaddset(&sig_set, SIGPOLL) sigaction(SIGPOLL, &s_action, 0) fcntl(sg_fd, F_SETOWN, getpid()) flags = fcntl(sg_fd, F_GETFL); fcntl(sg_fd, F_SETFL, flags | O_ASYNC)