[20241028]c function select例子.txt
--//使用strace跟踪mutex出现阻塞的情况下,测试出现使用函数是select。
--//17:38:23.920478 select(0, [], [], [], {0, 1000}) = 0 (Timeout) <0.001271>
--//我仔细看man -a select的相关文档,我的工作不用写这些代码也不熟悉C语言函数。
select, pselect, FD_CLR, FD_ISSET, FD_SET, FD_ZERO - synchronous I/O multiplexing
--//最后不是说明同步IO多路操作吗?怎么用在这里。
int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout);
nfds is the highest-numbered file descriptor in any of the three sets, plus 1.
--//17:38:23.920478 select(0, [], [], [], {0, 1000}) = 0 (Timeout) <0.001271>
--//注意传入的参数1 nfds=0,参数2,3,4为null,说明仅仅利用该函数做sleep,不知道我的理解是否正确。
--//也就是利用该函数做sleep 1000微秒,然后看看是否mutex是否释放。
--//不理解为什么不使用现成的nanosleep函数(strace 跟踪sleep命令可以发现),不过可以验证当参数1等于0的执行情况。
--//https://phoenixnap.com/kb/linux-select
#include <sys/time.h>
#include <sys/types.h>
#include<stdio.h>
#include <unistd.h>
int main()
{
fd_set rd;
struct timeval tv;
int err;
FD_ZERO( & rd);
FD_SET(0, & rd);
tv.tv_sec=4;
tv.tv_usec=0;
err=select(1, & rd, NULL, NULL, & tv);
if (err==0) //Timeout
{
printf("select timeout!!!\n");
}
else if (err == -1) //Fail
{
printf("failure to select\n");
}
else // Success
{
printf("data avalible\n");
}
return 0;
}
--//按照上面的例子修改如下:
$ cat select_test.c
#include <sys/time.h>
#include <sys/types.h>
#include<stdio.h>
#include <unistd.h>
int
main ()
{
struct timeval tv;
int err;
int i;
for (i = 1; i <= 3; i++)
{
tv.tv_sec = i;
tv.tv_usec = 0;
err = select (0, NULL, NULL, NULL, &tv);
if (err == 0) //Timeout
{
printf ("select timeout!!!\n");
}
else if (err == -1) //Fail
{
printf ("failure to select\n");
}
else // Success
{
printf ("data avalible\n");
}
}
err = select (0, NULL, NULL, NULL, &tv);
return 0;
}
--//注:每次都需要给tv结构赋值,不然变为{0, 0}.
$ gcc select_test.c -o select_test
$ strace -Ttt -e select ./select_test
08:28:37.059285 select(0, NULL, NULL, NULL, {1, 0}) = 0 (Timeout) <1.002518>
select timeout!!!
08:28:38.062190 select(0, NULL, NULL, NULL, {2, 0}) = 0 (Timeout) <2.021118>
select timeout!!!
08:28:40.083496 select(0, NULL, NULL, NULL, {3, 0}) = 0 (Timeout) <3.157576>
select timeout!!!
08:28:43.241184 select(0, NULL, NULL, NULL, {0, 0}) = 0 (Timeout) <0.000018>
08:28:43.241465 +++ exited with 0 +++
--//最后1次调用就是{0, 0}。
--//测试执行出现的是select(0, [], [], [], {0, 1000}) = 0 (Timeout) <0.001271>,而参数2是NULL,感觉应该查不多。
$ strace -Ttt -e select ./select_test
08:30:29.875425 select(0, NULL, NULL, NULL, {1, 0}) = 0 (Timeout) <1.001285>
select timeout!!!
08:30:30.877035 select(0, NULL, NULL, NULL, {2, 0}) = 0 (Timeout) <2.012231>
select timeout!!!
08:30:32.889398 select(0, NULL, NULL, NULL, {3, 0}^CProcess 4026 detached
<detached ...>
--//按ctrl+c中断。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/267265/viewspace-3044820/ ,如需转载,请注明出处,否则将追究法律责任。