logo

utils-std

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

nice.c (1928B)


  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. char *endptr = NULL;
  26. switch(c)
  27. {
  28. case 'n':
  29. incr = strtol(optarg, &endptr, 10);
  30. if(endptr && *endptr != 0) errno = EINVAL;
  31. if(errno != 0)
  32. {
  33. fprintf(stderr,
  34. "%s: error: Failed parsing '%s' as a number: %s\n",
  35. argv0,
  36. optarg,
  37. strerror(errno));
  38. usage();
  39. return 125;
  40. }
  41. break;
  42. case ':':
  43. fprintf(stderr, "%s: error: Missing operand for option: '-%c'\n", argv0, optopt);
  44. usage();
  45. return 125;
  46. case '?':
  47. fprintf(stderr, "%s: error: Unrecognised option: '-%c'\n", argv0, optopt);
  48. usage();
  49. return 125;
  50. default:
  51. abort();
  52. }
  53. }
  54. argc -= optind;
  55. argv += optind;
  56. if(argc == 0) return 0;
  57. errno = 0;
  58. if(nice((int)incr) == -1)
  59. {
  60. switch(errno)
  61. {
  62. case 0:
  63. break;
  64. case EPERM:
  65. fprintf(
  66. stderr, "%s: warning: Failed setting nice to %ld: %s\n", argv0, incr, strerror(errno));
  67. errno = 0;
  68. break;
  69. default:
  70. fprintf(stderr, "%s: error: Failed setting nice to %ld: %s\n", argv0, incr, strerror(errno));
  71. return 125;
  72. }
  73. }
  74. assert(argv[0]);
  75. if(execvp(argv[0], argv) < 0)
  76. {
  77. fprintf(stderr, "%s: error: Failed executing '%s': %s\n", argv0, argv[0], strerror(errno));
  78. return (errno == ENOENT) ? 127 : 126;
  79. }
  80. abort();
  81. }