Skip to content

Commit

Permalink
Fix #23: Support daemon(fork twice) for Darwin/OSX
Browse files Browse the repository at this point in the history
  • Loading branch information
winlinvip committed Oct 17, 2021
1 parent 52f19d6 commit 4bca722
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions event.c
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ static struct _st_kqdata {
int dellist_size;
int dellist_cnt;
int kq;
pid_t pid;
} *_st_kq_data;

#ifndef ST_KQ_MIN_EVTLIST_SIZE
Expand Down Expand Up @@ -463,6 +464,7 @@ ST_HIDDEN int _st_kq_init(void)
goto cleanup_kq;
}
fcntl(_st_kq_data->kq, F_SETFD, FD_CLOEXEC);
_st_kq_data->pid = getpid();

/*
* Allocate file descriptor data array.
Expand Down Expand Up @@ -698,6 +700,7 @@ ST_HIDDEN void _st_kq_dispatch(void)
tsp = &timeout;
}

retry_kevent:
/* Check for I/O operations */
nfd = kevent(_st_kq_data->kq,
_st_kq_data->addlist, _st_kq_data->addlist_cnt,
Expand Down Expand Up @@ -791,6 +794,23 @@ ST_HIDDEN void _st_kq_dispatch(void)
osfd = _st_kq_data->evtlist[i].ident;
_ST_KQ_REVENTS(osfd) = 0;
}
} else if (nfd < 0) {
if (errno == EBADF && _st_kq_data->pid != getpid()) {
/* We probably forked, reinitialize kqueue */
if ((_st_kq_data->kq = kqueue()) < 0) {
/* There is nothing we can do here, will retry later */
return;
}
fcntl(_st_kq_data->kq, F_SETFD, FD_CLOEXEC);
_st_kq_data->pid = getpid();
/* Re-register all descriptors on ioq with new kqueue */
memset(_st_kq_data->fd_data, 0, _st_kq_data->fd_data_size * sizeof(_kq_fd_data_t));
for (q = _ST_IOQ.next; q != &_ST_IOQ; q = q->next) {
pq = _ST_POLLQUEUE_PTR(q);
_st_kq_pollset_add(pq->pds, pq->npds);
}
goto retry_kevent;
}
}
}

Expand Down

0 comments on commit 4bca722

Please sign in to comment.