/* * Utility to run commands with arbitrary timeout value * v1.1 - cls@seawood.org */ /* The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is timeout.c, a timeout utility. The Initial Developer of the Original Code is Chris Seawood . Portions created by Chris Seawood are Copyright(C) 2006-2007 Chris Seawood. All Rights Reserved. */ #include #include #include #include #include #include #include int pid, repeat = 0, timeout = 0, use_kill = 0; char *cmd; void usage(char *name) { printf("Usage: %s -t seconds [-k] [-r] -- command [arg1] ...[argn]\n", name); exit(1); } void signal_handler(int signal) { if (signal == SIGALRM) { fprintf(stderr, "\nProcess '%s' has timed out after %d seconds!\n", cmd, timeout); if (use_kill) kill(pid, SIGKILL); else kill(pid, SIGTERM); } } int main(int argc, char *argv[]) { char *tostr = 0; int c, status; while ((c = getopt(argc, argv, "krt:")) > 0) { switch (c) { case 't': tostr = optarg; break; case 'r': repeat=1; break; case 'k': use_kill=1; break; } } if (!tostr) { usage(argv[0]); } else { timeout = strtol(tostr, 0, 10); if (errno != 0) { fprintf(stderr, "Could not convert argument to number: %s\n", strerror(errno)); exit(1); } if (timeout == 0) { fprintf(stderr, "Zero is not an acceptable timeout value\n"); exit(1); } } if (optind < argc) { cmd = argv[optind]; do { if ((pid = fork()) == 0) { execvp(argv[optind], argv+optind); fprintf(stderr, "Error running '%s': %s\n", argv[optind], strerror(errno)); } else { signal(SIGALRM, &signal_handler); alarm(timeout); waitpid(pid, &status, 0); } } while (!WIFEXITED(status) && repeat); if (WIFEXITED(status)) { exit(WEXITSTATUS(status)); } else { exit(-1); } } exit(1); }