diff --git a/bin/timeout/timeout.1 b/bin/timeout/timeout.1 index b81ce2f74625..3eacdd768410 100644 --- a/bin/timeout/timeout.1 +++ b/bin/timeout/timeout.1 @@ -1,232 +1,232 @@ .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2014 Baptiste Daroussin .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .Dd April 2, 2025 .Dt TIMEOUT 1 .Os .Sh NAME .Nm timeout .Nd run a command with a time limit .Sh SYNOPSIS .Nm +.Op Fl f | Fl -foreground .Op Fl k Ar time | Fl -kill-after Ar time +.Op Fl p | Fl -preserve-status .Op Fl s Ar signal | Fl -signal Ar signal .Op Fl v | Fl -verbose -.Op Fl -foreground -.Op Fl -preserve-status .Ar duration .Ar command .Op Ar arg ... .Sh DESCRIPTION .Nm Timeout starts the .Ar command with its .Ar arg list. If the .Ar command is still running after .Ar duration , it is killed by sending the .Ar signal , or .Dv SIGTERM if the .Fl s option is unspecified. The special .Ar duration , zero, signifies no limit. Therefore, a signal is never sent if .Ar duration is 0. .Pp The options are as follows: .Bl -tag -width indent -.It Fl -foreground +.It Fl f , Fl -foreground Only time out the .Ar command itself, but do not propagate signals to its descendants. .It Fl k Ar time , Fl -kill-after Ar time Send a .Dv SIGKILL signal if .Ar command is still running after .Ar time since the first signal was sent. -.It Fl -preserve-status +.It Fl p , Fl -preserve-status Always exit with the same status as .Ar command , even if the timeout was reached. .It Fl s Ar signal , Fl -signal Ar signal Specify the signal to send on timeout. By default, .Dv SIGTERM is sent. .It Fl v , Fl -verbose Show information to stderr about any signal sent on timeout. .El .Ss Duration Format The .Ar duration and .Ar time are non-negative integer or real (decimal) numbers, with an optional suffix specifying the unit. Values without an explicit unit are interpreted as seconds. .Pp Supported unit suffixes are: .Bl -tag -offset indent -width indent -compact .It Cm s seconds .It Cm m minutes .It Cm h hours .It Cm d days .El .Sh EXIT STATUS If the timeout was not reached, the exit status of .Ar command is returned. .Pp If the timeout was reached and .Fl -preserve-status is set, the exit status of .Ar command is returned. If .Fl -preserve-status is not set, an exit status of 124 is returned. .Pp If an invalid parameter is passed to .Fl s or .Fl k , the exit status returned is 125. .Pp If .Ar command is an otherwise invalid program, the exit status returned is 126. .Pp If .Ar command refers to a non-existing program, the exit status returned is 127. .Pp If .Ar command exits after receiving a signal, the exit status returned is the signal number plus 128. .Sh EXAMPLES Run .Xr sleep 1 with a time limit of 4 seconds. Since the command completes in 2 seconds, the exit status is 0: .Bd -literal -offset indent $ timeout 4 sleep 2 $ echo $? 0 .Ed .Pp Run .Xr sleep 1 for 4 seconds and terminate process after 2 seconds. The exit status is 124 since .Fl -preserve-status is not used: .Bd -literal -offset indent $ timeout 2 sleep 4 $ echo $? 124 .Ed .Pp Same as above but preserving status. The exit status is 128 + signal number (15 for .Dv SIGTERM ) : .Bd -literal -offset indent $ timeout --preserve-status 2 sleep 4 $ echo $? 143 .Ed .Pp Same as above but sending .Dv SIGALRM (signal number 14) instead of .Dv SIGTERM : .Bd -literal -offset indent $ timeout --preserve-status -s SIGALRM 2 sleep 4 $ echo $? 142 .Ed .Pp Try to .Xr fetch 1 the PDF version of the .Fx Handbook. Send a .Dv SIGTERM signal after 1 minute and send a .Dv SIGKILL signal 5 seconds later if the process refuses to stop: .Bd -literal -offset indent $ timeout -k 5s 1m fetch \\ > https://download.freebsd.org/ftp/doc/en/books/handbook/book.pdf .Ed .Sh SEE ALSO .Xr kill 1 , .Xr nohup 1 , .Xr signal 3 , .Xr daemon 8 .Sh STANDARDS The .Nm utility is expected to conform to the .St -p1003.1-2024 specification. .Sh HISTORY The .Nm command first appeared in .Fx 10.3 . .Pp The .Fx work is compatible with GNU .Nm by .An Padraig Brady , from GNU Coreutils 8.21. The .Nm utility first appeared in GNU Coreutils 7.0. .Sh AUTHORS .An Baptiste Daroussin Aq Mt bapt@FreeBSD.org and .An Vsevolod Stakhov Aq Mt vsevolod@FreeBSD.org diff --git a/bin/timeout/timeout.c b/bin/timeout/timeout.c index 4c81b64cd2b6..7e4009f8ac8a 100644 --- a/bin/timeout/timeout.c +++ b/bin/timeout/timeout.c @@ -1,365 +1,370 @@ /*- * Copyright (c) 2014 Baptiste Daroussin * Copyright (c) 2014 Vsevolod Stakhov * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #define EXIT_TIMEOUT 124 #define EXIT_INVALID 125 #define EXIT_CMD_ERROR 126 #define EXIT_CMD_NOENT 127 static volatile sig_atomic_t sig_chld = 0; static volatile sig_atomic_t sig_term = 0; static volatile sig_atomic_t sig_alrm = 0; static volatile sig_atomic_t sig_ign = 0; static const char *command = NULL; static bool verbose = false; static void __dead2 usage(void) { fprintf(stderr, - "Usage: %s [--foreground] [-k time | --kill-after time]" - " [--preserve-status] [-s signal | --signal signal] " + "Usage: %s [-f | --foreground] [-k time | --kill-after time]" + " [-p | --preserve-status] [-s signal | --signal signal] " " [-v | --verbose] [arg ...]\n", getprogname()); exit(EXIT_FAILURE); } static double parse_duration(const char *duration) { double ret; char *suffix; ret = strtod(duration, &suffix); if (suffix == duration) errx(EXIT_INVALID, "duration is not a number"); if (*suffix == '\0') return (ret); if (suffix[1] != '\0') errx(EXIT_INVALID, "duration unit suffix too long"); switch (*suffix) { case 's': break; case 'm': ret *= 60; break; case 'h': ret *= 60 * 60; break; case 'd': ret *= 60 * 60 * 24; break; default: errx(EXIT_INVALID, "duration unit suffix invalid"); } if (ret < 0 || ret >= 100000000UL) errx(EXIT_INVALID, "duration out of range"); return (ret); } static int parse_signal(const char *str) { int sig, i; const char *errstr; sig = strtonum(str, 1, sys_nsig - 1, &errstr); if (errstr == NULL) return (sig); if (strncasecmp(str, "SIG", 3) == 0) str += 3; for (i = 1; i < sys_nsig; i++) { if (strcasecmp(str, sys_signame[i]) == 0) return (i); } errx(EXIT_INVALID, "invalid signal"); } static void sig_handler(int signo) { if (sig_ign != 0 && signo == sig_ign) { sig_ign = 0; return; } switch (signo) { case SIGINT: case SIGHUP: case SIGQUIT: case SIGTERM: sig_term = signo; break; case SIGCHLD: sig_chld = 1; break; case SIGALRM: sig_alrm = 1; break; } } static void send_sig(pid_t pid, int signo) { if (verbose) { warnx("sending signal %s(%d) to command '%s'", sys_signame[signo], signo, command); } kill(pid, signo); } static void set_interval(double iv) { struct itimerval tim; memset(&tim, 0, sizeof(tim)); if (iv > 0) { tim.it_value.tv_sec = (time_t)iv; iv -= (double)(time_t)iv; tim.it_value.tv_usec = (suseconds_t)(iv * 1000000UL); } if (setitimer(ITIMER_REAL, &tim, NULL) == -1) err(EXIT_FAILURE, "setitimer()"); } int main(int argc, char **argv) { int ch, status, sig; - int foreground, preserve; int pstat = 0; int killsig = SIGTERM; size_t i; pid_t pid, cpid; double first_kill; - double second_kill; + double second_kill = 0; + bool foreground = false; + bool preserve = false; bool timedout = false; bool do_second_kill = false; bool child_done = false; struct sigaction signals; struct procctl_reaper_status info; struct procctl_reaper_kill killemall; int signums[] = { -1, SIGTERM, SIGINT, SIGHUP, SIGCHLD, SIGALRM, SIGQUIT, }; - foreground = preserve = 0; - second_kill = 0; - + const char optstr[] = "+fhk:ps:v"; const struct option longopts[] = { - { "foreground", no_argument, &foreground, 1 }, - { "help", no_argument, NULL, 'h' }, - { "kill-after", required_argument, NULL, 'k' }, - { "preserve-status", no_argument, &preserve, 1 }, - { "signal", required_argument, NULL, 's' }, - { "verbose", no_argument, NULL, 'v' }, - { NULL, 0, NULL, 0 }, + { "foreground", no_argument, NULL, 'f' }, + { "help", no_argument, NULL, 'h' }, + { "kill-after", required_argument, NULL, 'k' }, + { "preserve-status", no_argument, NULL, 'p' }, + { "signal", required_argument, NULL, 's' }, + { "verbose", no_argument, NULL, 'v' }, + { NULL, 0, NULL, 0 }, }; - while ((ch = getopt_long(argc, argv, "+k:s:vh", longopts, NULL)) != -1) { + while ((ch = getopt_long(argc, argv, optstr, longopts, NULL)) != -1) { switch (ch) { + case 'f': + foreground = true; + break; case 'k': do_second_kill = true; second_kill = parse_duration(optarg); break; + case 'p': + preserve = true; + break; case 's': killsig = parse_signal(optarg); break; case 'v': verbose = true; break; case 0: break; default: usage(); } } argc -= optind; argv += optind; if (argc < 2) usage(); first_kill = parse_duration(argv[0]); argc--; argv++; command = argv[0]; if (!foreground) { /* Acquire a reaper */ if (procctl(P_PID, getpid(), PROC_REAP_ACQUIRE, NULL) == -1) err(EXIT_FAILURE, "procctl(PROC_REAP_ACQUIRE)"); } memset(&signals, 0, sizeof(signals)); sigemptyset(&signals.sa_mask); if (killsig != SIGKILL && killsig != SIGSTOP) signums[0] = killsig; for (i = 0; i < sizeof(signums) / sizeof(signums[0]); i++) sigaddset(&signals.sa_mask, signums[i]); signals.sa_handler = sig_handler; signals.sa_flags = SA_RESTART; for (i = 0; i < sizeof(signums) / sizeof(signums[0]); i++) { if (signums[i] > 0 && sigaction(signums[i], &signals, NULL) == -1) err(EXIT_FAILURE, "sigaction()"); } /* Don't stop if background child needs TTY */ signal(SIGTTIN, SIG_IGN); signal(SIGTTOU, SIG_IGN); pid = fork(); if (pid == -1) { err(EXIT_FAILURE, "fork()"); } else if (pid == 0) { /* child process */ signal(SIGTTIN, SIG_DFL); signal(SIGTTOU, SIG_DFL); execvp(argv[0], argv); warn("exec(%s)", argv[0]); _exit(errno == ENOENT ? EXIT_CMD_NOENT : EXIT_CMD_ERROR); } /* parent continues here */ if (sigprocmask(SIG_BLOCK, &signals.sa_mask, NULL) == -1) err(EXIT_FAILURE, "sigprocmask()"); set_interval(first_kill); sigemptyset(&signals.sa_mask); for (;;) { sigsuspend(&signals.sa_mask); if (sig_chld) { sig_chld = 0; while ((cpid = waitpid(-1, &status, WNOHANG)) != 0) { if (cpid < 0) { if (errno != EINTR) break; } else if (cpid == pid) { pstat = status; child_done = true; } } if (child_done) { if (foreground) { break; } else { procctl(P_PID, getpid(), PROC_REAP_STATUS, &info); if (info.rs_children == 0) break; } } } else if (sig_alrm || sig_term) { if (sig_alrm) { sig = killsig; sig_alrm = 0; timedout = true; } else { sig = sig_term; sig_term = 0; } if (foreground) { send_sig(pid, sig); } else { killemall.rk_sig = sig; killemall.rk_flags = 0; procctl(P_PID, getpid(), PROC_REAP_KILL, &killemall); } if (do_second_kill) { set_interval(second_kill); do_second_kill = false; sig_ign = killsig; killsig = SIGKILL; } else { break; } } } while (!child_done && wait(&pstat) == -1) { if (errno != EINTR) err(EXIT_FAILURE, "wait()"); } if (!foreground) procctl(P_PID, getpid(), PROC_REAP_RELEASE, NULL); if (timedout && !preserve) { pstat = EXIT_TIMEOUT; } else { if (WIFEXITED(pstat)) pstat = WEXITSTATUS(pstat); else if (WIFSIGNALED(pstat)) pstat = 128 + WTERMSIG(pstat); } return (pstat); }