Skip to content

Commit

Permalink
perf: kill tty which inactive in 10 minutes
Browse files Browse the repository at this point in the history
Signed-off-by: Jianhui Zhao <zhaojh329@gmail.com>
  • Loading branch information
zhaojh329 committed Sep 14, 2021
1 parent 50c2171 commit 57e23be
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/rtty.c
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ static void del_tty(struct tty *tty)

ev_io_stop(loop, &tty->ior);
ev_io_stop(loop, &tty->iow);
ev_timer_stop(loop, &tty->tmr);
ev_child_stop(loop, &tty->cw);

buffer_free(&tty->wb);
Expand Down Expand Up @@ -84,6 +85,8 @@ static void pty_on_read(struct ev_loop *loop, struct ev_io *w, int revents)
static uint8_t buf[4096];
int len;

tty->active = ev_now(loop);

while (1) {
len = read(w->fd, buf, sizeof(buf));
if (likely(len > 0))
Expand Down Expand Up @@ -141,6 +144,20 @@ static void pty_on_exit(struct ev_loop *loop, struct ev_child *w, int revents)
del_tty(tty);
}

static void tty_timer_cb(struct ev_loop *loop, struct ev_timer *w, int revents)
{
struct tty *tty = container_of(w, struct tty, tmr);
ev_tstamp now = ev_now(loop);

if (now - tty->active < RTTY_TTY_TIMEOUT)
return;

ev_timer_stop(loop, w);
kill(tty->pid, SIGTERM);

log_err("tty(%d) inactive over %ds, now kill it\n", tty->sid, RTTY_TTY_TIMEOUT);
}

static void tty_login(struct rtty *rtty)
{
struct tty *tty;
Expand Down Expand Up @@ -190,6 +207,9 @@ static void tty_login(struct rtty *rtty)
ev_child_init(&tty->cw, pty_on_exit, pid, 0);
ev_child_start(rtty->loop, &tty->cw);

ev_timer_init(&tty->tmr, tty_timer_cb, 3, 3);
ev_timer_start(rtty->loop, &tty->tmr);

rtty->ttys[sid] = tty;

buffer_put_u16be(&rtty->wb, 2);
Expand All @@ -215,6 +235,8 @@ static void write_data_to_tty(struct rtty *rtty, int sid, int len)
return;
}

tty->active = ev_now(rtty->loop);

buffer_put_data(&tty->wb, buffer_data(&rtty->rb), len);
buffer_pull(&rtty->rb, NULL, len);
ev_io_start(rtty->loop, &tty->iow);
Expand Down
3 changes: 3 additions & 0 deletions src/rtty.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@

#define RTTY_MAX_TTY 5
#define RTTY_HEARTBEAT_INTEVAL 5.0
#define RTTY_TTY_TIMEOUT 600

enum {
MSG_TYPE_REGISTER,
Expand All @@ -64,6 +65,8 @@ struct tty {
struct ev_child cw;
struct buffer wb;
struct rtty *rtty;
ev_tstamp active;
struct ev_timer tmr;
};

struct rtty {
Expand Down

0 comments on commit 57e23be

Please sign in to comment.