You can use the select to monitor a file or a group of file descriptors until they have input available.
(您可以使用select监视一个文件或一组文件描述符,直到它们具有可用的输入。)
Depending on the structure of your program you could also use asynchronous input where a callback is called when I/O is signaled as ready for a given file descriptor. (根据程序的结构,您还可以使用异步输入,其中当发信号通知I / O准备好给定文件描述符时,将调用回调。)
The rough snippet below shows the necessary methodology to allow for the callback action_handler
to be called when input becomes available on the target file description, which emittes SIGIO.
(下面的粗略片段显示了必要的方法,该方法允许在目标文件描述中的输入变为可用时调用回调action_handler
,从而发出SIGIO。)
This allows for the input to be processed when it arrives, if it arrives. (这允许输入到达时对其进行处理(如果到达)。)
Using a socket (lets assume UDP) you would have something similar to the following. (使用套接字(假设使用UDP),您将具有类似于以下内容的内容。)
#include <fcntl.h>
#include <signal.h>
#include <sys/socket.h>
...
create and bind socket
...
/** Set sigaction to use sigaction callback and not handler */
act.sa_flags = SA_SIGINFO; // Enables sigaction instead of handler
act.sa_sigaction = action_handler; // Callback function
/** Set mask to ignore all signals except SIGIO during execution of handler */
sigfillset(&act.sa_mask); // Mask all
sigdelset(&act.sa_mask, SIGIO); // Clear SIGIO from mask
/** Set callback for SIGIO */
sigaction(SIGIO, &act, NULL)
/** Set socket io signals to async and make sure SIGIO is sent to current
* process when a TCP connection is made on the socket
* */
file_status = fcntl(socket_fd, F_GETFL); // Get current status
file_status |= O_ASYNC | O_NONBLOCK;
fcntl(socket_fd, F_SETFL, file_status); // Set modified status flags
fcntl(socket_fd, F_SETSIG, SIGIO); // Produce a SIGIO signal when i/o is possible
fcntl(socket_fd, F_SETOWN, getpid()); // Make sure SIGIO signal is sent to current process
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…