Skip to content

Commit

Permalink
perf: epoll -> poll, do not waitpid on EAGAIN
Browse files Browse the repository at this point in the history
  • Loading branch information
horror-proton committed Dec 23, 2023
1 parent 2680b9a commit dae6417
Showing 1 changed file with 7 additions and 11 deletions.
18 changes: 7 additions & 11 deletions src/MaaCore/Controller/Platform/PosixIO.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

#include <fcntl.h>
#include <signal.h>
#include <sys/epoll.h>
#include <sys/errno.h>
#include <sys/poll.h>
#include <sys/socket.h>
#ifndef __APPLE__
#include <sys/prctl.h>
Expand Down Expand Up @@ -120,16 +120,11 @@ std::optional<int> asst::PosixIO::call_command(const std::string& cmd, const boo
// has the child exited in the loop?
bool child_exited = false;

static const auto epfd = ::epoll_create1(EPOLL_CLOEXEC);
{
::epoll_event ev {};
ev.events = POLL_IN;
ev.data.fd = pipe_out[PIPE_READ];
::epoll_ctl(epfd, EPOLL_CTL_ADD, pipe_out[PIPE_READ], &ev);
}

// whether we recv_by_socket or not, we have to
// drain the output pipe so that it doesn't block I/O.
std::array<::pollfd, 1> events {
::pollfd { .fd = pipe_out[PIPE_READ], .events = POLLIN },
};
while (true) {
ssize_t read_num = ::read(pipe_out[PIPE_READ], pipe_buffer.get(), pipe_buffer.size());
while (read_num > 0) {
Expand All @@ -138,6 +133,9 @@ std::optional<int> asst::PosixIO::call_command(const std::string& cmd, const boo
}
read_num = ::read(pipe_out[PIPE_READ], pipe_buffer.get(), pipe_buffer.size());
}
if (read_num == -1 && errno == EAGAIN) {
if (::poll(events.data(), events.size(), 1000) > 0) continue;
}
if (::waitpid(m_child, &exit_ret, WNOHANG) != 0) {
child_exited = true;
break;
Expand All @@ -146,8 +144,6 @@ std::optional<int> asst::PosixIO::call_command(const std::string& cmd, const boo
Log.warn("timeout when reading the output, killing child:", m_child);
break;
}
std::array<::epoll_event, 1> events {};
::epoll_wait(epfd, events.data(), 1, 1000);
}

::close(pipe_in[PIPE_WRITE]);
Expand Down

0 comments on commit dae6417

Please sign in to comment.