7.7. fcntl(sg_fd, F_SETFL, oflags | FASYNC)

fcntl(int sg_fd, int cmd, long arg). 在与 sg 文件描述符关联时,此系统调用有多种用途。以下伪代码显示了用于扫描 sg 设备的有用代码,注意不要被另一个进程的 O_EXCL 锁所困,并且在找到合适的设备时,切换到正常的阻塞 io。 sg_scan 实用程序中有一个此逻辑的工作示例。
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 */

sg 驱动程序支持异步通知。这是一种非阻塞的操作模式,当驱动程序从设备接收到数据,可以进行 read() 操作时,它会向拥有进程发送 SIGPOLL(又名 SIGIO)信号。以下是 sg_poll 测试程序中的代码片段。
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)