这是我的剪切代码,它只是一个监听tcp连接的简单服务器。如果我只是将fd传递给epoll_event数据但它现在需要传递一个指向结构数组的指针而我无法使它工作。我的完整代码目前正在编译,但在执行时会给我一个general protection ip:406de3 sp:7fffbc86a070 error:
。你可以检查一下我的代码,看看是否有特别指针的问题。
#define MAX_EVENTS 16
struct client_data{
char id;
char active;
char disabled;
int fd;
};
struct epoll_event ev;
struct epoll_event events[MAX_EVENTS];
struct client_data client[16];
int listener_fd = open_socket_function_here();
int running = 1;
ev.events = EPOLLIN;
ev.data.ptr = &listener_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listener_fd, &ev) < 0) {
/* error handling here */
return -1;
}
while ( running ) {
int num_events = epoll_wait(epoll_fd, events, MAX_EVENTS, 5000);
/* Check if epoll actually succeed */
if ( num_events == -1 ){
fprintf (stderr,"Error epoll_wait : %s\n", strerror(errno));
return -1;
}
else if ( num_events == 0 ){
/* timeout; no event detected */
}
else{
for ( i = 0; i < num_events; i++ ){
if ( ( events[i].data.ptr == &listener_fd ) && events[i].events & EPOLLIN ){
int new_client_id = accept_new_tcp_client( listener_fd ); /* this function returns an id not a file descriptor. The fd is saved in client array using the index new_client_id*/
/* Do we have a valid client_id */
if ( new_client_id >= 0 ){
/* Add this new socket to EPOLL */
ev.events = EPOLLIN;
ev.data.ptr = &client[new_client_id];
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, users[new_client_id].tcp_socket, &ev) < 0) {
close(client[new_client_id].fd);
client[new_client_id].active = 0;
client[new_client_id].fd = -1;
}
}
}
else{
int current_id, current_fd;
struct client_data *event_ptr = (struct client_data *)events[i].data.ptr;
current_id = event_ptr->id;
current_fd = event_ptr->fd;
/* Client uploaded data */
if (events[i].events & EPOLLIN ) {
/* pass the fd and id for processing */
process_data(current_fd,current_id);
}
}
}
}
}