pselect为select的迭代升级版,示例中包含select与pselect的使用,其中fd用了pipe的,输入参数1需要根据要求“nfds should be set to the highest-numbered file descriptor in any of the three sets, plus 1. The indicated file descriptors in each set are checked, up to this limit (but see BUGS).”!——即在最大fd值基础上+1.
#include "It_test_IO.h"
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "sys/select.h"
static UINT32 Testcase1(VOID)
{
static const int TAR_STR_LEN = 12;
int pipeFd[2], ret; /* 2, pipe return 2 file descirpter */
fd_set reads;
ret = pipe(pipeFd);
ICUNIT_GOTO_EQUAL(ret, 0, ret, EXIT);
ret = write(pipeFd[1], "Hello World", TAR_STR_LEN);
printf("write first status: %d\n", ret);
ICUNIT_GOTO_EQUAL(ret, TAR_STR_LEN, ret, EXIT);
FD_ZERO(&reads);
FD_SET(pipeFd[0], &reads);
ret = select(pipeFd[0] + 1, &reads, NULL, NULL, NULL);
ICUNIT_GOTO_EQUAL(ret, 1, ret, EXIT);
ret = FD_ISSET(pipeFd[0], &reads);
ICUNIT_GOTO_NOT_EQUAL(ret, 0, ret, EXIT);
close(pipeFd[0]);
close(pipeFd[1]);
printf("-------------------FD_ISSET ok------------\n");
return LOS_OK;
EXIT:
close(pipeFd[0]);
close(pipeFd[1]);
return LOS_NOK;
}
static UINT32 testcase(VOID)
{
fd_set rfds;
struct timespec tv;
int retval;
pid_t pid;
int pipeFd[2];
char buffer[40];
retval = Testcase1(); /* first check select works */
ICUNIT_GOTO_EQUAL(retval, 0, retval, OUT);
retval = pipe(pipeFd);
ICUNIT_GOTO_EQUAL(retval, 0, retval, OUT);
printf("[INFO]pipeFd[0]=%d,pipeFd[1]=%d\n", pipeFd[0], pipeFd[1]);
/* Watch fd to see when it has input. */
FD_ZERO(&rfds);
FD_SET(pipeFd[0], &rfds);
/* Wait up to three seconds. */
tv.tv_sec = 3;
tv.tv_nsec = 5;
pid = fork();
if (pid == 0) {
printf("[INFO]FUNC=%s,LINE=%d,pid=%d\n", __FUNCTION__, __LINE__, pid);
close(pipeFd[1]);
retval = pselect(pipeFd[0] + 1, &rfds, nullptr, nullptr, &tv, (const sigset_t *)((long[]){ 0, _NSIG/8 }));
ICUNIT_GOTO_EQUAL(retval, 1, retval, OUT);
close(pipeFd[0]);
if (retval == -1) {
perror("pselect()");
return LOS_NOK;
} else if (retval) {
printf("Data is available now.\n");
return LOS_OK;
} else { /* FD_ISSET(0, &rfds) will be true. */
printf("No data within three seconds.\n");
return LOS_NOK;
}
} else {
sleep(1);
printf("[INFO]FUNC=%s,LINE=%d,pid=%d\n", __FUNCTION__, __LINE__, pid);
printf("[INFO]write to fd=%d,after sleep(1).\n", pipeFd[1]);
close(pipeFd[0]);
retval = write(pipeFd[1], "0123456789012345678901234567890123456789", 40); /* write 40 bytes to stdin(fd 0) */
ICUNIT_GOTO_EQUAL(retval, 40, retval, OUT);
close(pipeFd[1]);
}
return LOS_OK;
OUT:
return LOS_NOK;
}
VOID main (VOID)
{
TEST_ADD_CASE(__FUNCTION__, testcase, TEST_LIB, TEST_LIBC, TEST_LEVEL1, TEST_FUNCTION);
}