写Linux程序经常会看到&和|按位操作符号,具体就是内核提供的宏之间进行按位操作。
他们具体什么意思?
我们在macOS中看到poll.h的事件的宏定义:
#define POLLIN 0x0001 /* any readable data available */ #define POLLPRI 0x0002 /* OOB/Urgent readable data */ #define POLLOUT 0x0004 /* file descriptor is writeable */ #define POLLRDNORM 0x0040 /* non-OOB/URG data available */ #define POLLWRNORM POLLOUT /* no write type differentiation */ #define POLLRDBAND 0x0080 /* OOB/Urgent readable data */ #define POLLWRBAND 0x0100 /* OOB/Urgent data can be written */ /* * FreeBSD extensions: polling on a regular file might return one * of these events (currently only supported on local filesystems). */ #define POLLEXTEND 0x0200 /* file may have been extended */ #define POLLATTRIB 0x0400 /* file attributes may have changed */ #define POLLNLINK 0x0800 /* (un)link/rename may have happened */ #define POLLWRITE 0x1000 /* file's contents may have changed */
用到poll网络模型时候,我们会使用 POLLIN | POLLRDHUP | POLLERR 这样的操作,通过上面的源码可以看到这些宏是十六进制数,0x0001的二进制是1,0x0002是10,0x0004是100,0x0040是1000000,ox0200是1000000000,0x0400是10000000000,0x0800是100000000000,0x1000是1000000000000。
因此给某个文件描述符添加某些事件时会用到按位操作,在二进制位上进行运算,保证计算速度。