某些操作系统上没有 timeout 命令,那就写一个

0阅读 0评论2025-09-04 snow888
分类:C/C++

话不多说,直接贴代码。

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/wait.h>
  5. #include <signal.h>

  6. pid_t child_pid = -1;

  7. void alarm_handler(int sig) {
  8.     if (child_pid != -1) {
  9.         kill(child_pid, SIGTERM);
  10.     }
  11. }

  12. int isNumber(const char *s)
  13. {
  14.     int i = 0;
  15.     for ( i = 0 ; i < strlen((const char *)s) ; i++)
  16.     {
  17.         if ( !isdigit(s[i]))
  18.         {
  19.             return 1;
  20.         }
  21.     }
  22.     return 0;
  23. }

  24. int main(int argc, char *argv[]) {
  25.     if (argc < 3) {
  26.         fprintf(stderr, "Usage: %s [args...]\n", argv[0]);
  27.         return 1;
  28.     } else if ( isNumber(argv[1]) != 0 )
  29.     {
  30.         fprintf(stderr, "Usage: %s [args...]\n", argv[0]);
  31.         return 1;
  32.     }


  33.     int timeout = atoi(argv[1]);
  34.     if (timeout <= 0) {
  35.         fprintf(stderr, "Timeout must be a positive integer\n");
  36.         return 1;
  37.     }

  38.     signal(SIGALRM, alarm_handler);
  39.     alarm(timeout);

  40.     child_pid = fork();
  41.     if (child_pid == 0) {
  42.         // Child process
  43.     if ( argc < 4 ){
  44.              argv[3]=NULL;
  45.     }
  46.         execvp(argv[2], &argv[2]);
  47.         perror("execvp");
  48.         exit(1);
  49.     } else if (child_pid > 0) {
  50.         // Parent process
  51.         int status;
  52.         waitpid(child_pid, &status, 0);
  53.         alarm(0); // Cancel the alarm
  54.         return WIFEXITED(status) ? WEXITSTATUS(status) : 1;
  55.     } else {
  56.         perror("fork");
  57.         return 1;
  58.     }
  59. }

上一篇:妈的,关于 static 被网络上的信息带偏了,还以为自己理解错误呢
下一篇:从 Windows 桌面转向Unix/Linux,我们需要准备什么?