logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git

nice.c (1973B)


  1. // utils-std: Collection of commonly available Unix tools
  2. // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _POSIX_C_SOURCE 200809L
  5. #define _XOPEN_SOURCE 700 // nice() is in XSI
  6. #include <assert.h>
  7. #include <errno.h>
  8. #include <stdio.h> // fprintf
  9. #include <stdlib.h> // abort
  10. #include <string.h> // strerror
  11. #include <unistd.h> // getopt, nice
  12. const char *argv0 = "nice";
  13. static void
  14. usage(void)
  15. {
  16. fprintf(stderr, "Usage: nice [-n increment] command [argument ...]\n");
  17. }
  18. int
  19. main(int argc, char *argv[])
  20. {
  21. long incr = 0;
  22. int c = -1;
  23. while((c = getopt(argc, argv, ":n:")) != -1)
  24. {
  25. switch(c)
  26. {
  27. case 'n':
  28. assert(errno == 0);
  29. char *endptr = NULL;
  30. incr = strtol(optarg, &endptr, 10);
  31. if(endptr && *endptr != 0) errno = EINVAL;
  32. if(errno != 0)
  33. {
  34. fprintf(stderr,
  35. "%s: error: Failed parsing '%s' as a number: %s\n",
  36. argv0,
  37. optarg,
  38. strerror(errno));
  39. usage();
  40. return 125;
  41. }
  42. break;
  43. case ':':
  44. fprintf(stderr, "%s: error: Missing operand for option: '-%c'\n", argv0, optopt);
  45. usage();
  46. return 125;
  47. case '?':
  48. fprintf(stderr, "%s: error: Unrecognised option: '-%c'\n", argv0, optopt);
  49. usage();
  50. return 125;
  51. default:
  52. abort();
  53. }
  54. }
  55. argc -= optind;
  56. argv += optind;
  57. if(argc == 0) return 0;
  58. errno = 0;
  59. if(nice((int)incr) == -1)
  60. {
  61. switch(errno)
  62. {
  63. case 0:
  64. break;
  65. case EPERM:
  66. fprintf(
  67. stderr, "%s: warning: Failed setting nice to %ld: %s\n", argv0, incr, strerror(errno));
  68. errno = 0;
  69. break;
  70. default:
  71. fprintf(stderr, "%s: error: Failed setting nice to %ld: %s\n", argv0, incr, strerror(errno));
  72. return 125;
  73. }
  74. }
  75. assert(argv[0]);
  76. assert(errno == 0);
  77. if(execvp(argv[0], argv) < 0)
  78. {
  79. fprintf(stderr, "%s: error: Failed executing '%s': %s\n", argv0, argv[0], strerror(errno));
  80. return (errno == ENOENT) ? 127 : 126;
  81. }
  82. abort();
  83. }