logo

utils-std

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

nice.c (1926B)


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