1,給執行epoll_wait的程序發signal。linux
#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源代碼c++
執行方法:git
1,執行程序github
2,先用下面的命令找到當前執行程序的PIDshell
ps -e | grep a.out
結果:微信
ys@ys-VirtualBox:~/cpp/network$ ps -e | grep a.out 2882 pts/0 00:00:00 a.out
3,給個執行中的程序發signalsocket
kill -s SIGUSR1 2882
結果:ide
before epoll_wait signal called after epoll_wait:-1 4 perror after epoll_wait: Interrupted system call
#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源代碼oop