linux epoll系列5 解除epoll_wait状态

有时候会有解除epoll_wait状态的需求。

实现方法:

1,给执行epoll_wait的程序发signal。

2,使用sockpair。

1,给执行epoll_wait的程序发signal。

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <sys/epoll.h> void sigusr1_handler(int sig){
write(fileno(stdout), "signal called\n", 14);
} int main(){
int nfds;
int epfd; signal(SIGUSR1, sigusr1_handler); epfd = epoll_create(1);
if(epfd < 0){
perror("epoll_crreate");
return 1;
} printf("before epoll_wait\n"); //一直等下去
nfds = epoll_wait(epfd, NULL, 1, -1);
printf("after epoll_wait:%d\n", nfds); printf("%d\n", errno);
perror("perror after epoll_wait"); return 0;
}

github源代码

执行方法:

1,执行程序

2,先用下面的命令找到当前执行程序的PID

ps -e | grep a.out

结果:

ys@ys-VirtualBox:~/cpp/network$ ps -e | grep a.out
2882 pts/0 00:00:00 a.out

3,给个执行中的程序发signal

kill -s SIGUSR1 2882

结果:

before epoll_wait
signal called
after epoll_wait:-1
4
perror after epoll_wait: Interrupted system call

2,使用sockpair。

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h> #define EVENTS 8 int soc[2]; void processA(){
sleep(3);
printf("processA: send message\n");
write(soc[0], "HELLO\n", 6);
return;
} void processB(){
int epfd;
epoll_event ev, ev_ret[EVENTS];
int nfds;
int i;
char buf[128]; epfd = epoll_create(1);
if(epfd < 0){
perror("epoll_create");
return ;
} memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;
ev.data.fd = soc[1]; if(epoll_ctl(epfd, EPOLL_CTL_ADD, soc[1], &ev) != 0){
perror("epoll_clt");
return ;
} memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;
ev.data.fd = fileno(stdin); if(epoll_ctl(epfd, EPOLL_CTL_ADD, fileno(stdin), &ev) != 0){
perror("epoll_clt1");
return ;
} while(1){
printf("before epoll_wait\n"); nfds = epoll_wait(epfd, ev_ret, EVENTS , -1);
if(nfds < 0){
perror("epoll_wait");
return;
} printf("after epoll_wait\n"); for(i = 0; i < nfds; ++i){
if(ev_ret[i].data.fd == soc[1]){
printf("processB:break message from socketpair\n");
goto outofloop;
}
else if(ev_ret[i].data.fd == fileno(stdin)){
read(fileno(stdin), buf, sizeof(buf));
printf("processB:input from stdin\n");
}
}
} outofloop:
printf("process B:outside of loop\n"); return ;
}
int main(){
int ret; ret = socketpair(AF_UNIX, SOCK_STREAM, 0, soc);
if(ret != 0){
perror("socketpair");
return 1;
} if(fork() == 0){
processA();
}
else{
processB();
} return 0;
}

github源代码

c/c++ 学习互助QQ群:877684253

c/c++ llinux epoll系列5 解除epoll_wait状态-LMLPHP

本人微信:xiaoshitou5854

04-29 02:21