logo

utils-std

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

mkfifo.c (1972B)


  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. #include "../config.h"
  6. #include "../libutils/getopt_nolong.h"
  7. #include "../libutils/mode.h"
  8. #include <errno.h>
  9. #include <stdio.h> // fprintf
  10. #include <stdlib.h> // abort
  11. #include <string.h> // strerror
  12. #include <sys/stat.h> // mkfifo
  13. #include <unistd.h> // getopt
  14. #ifdef HAS_GETOPT_LONG
  15. #include <getopt.h>
  16. #endif
  17. mode_t filemask;
  18. const char *argv0 = "mkfifo";
  19. static void
  20. usage(void)
  21. {
  22. fprintf(stderr, "Usage: mkfifo [-m mode] file\n");
  23. }
  24. int
  25. main(int argc, char *argv[])
  26. {
  27. mode_t mode = 0666;
  28. const char *errstr = NULL;
  29. #ifdef HAS_GETOPT_LONG
  30. // Strictly for GNUisms compatibility so no long-only options
  31. // clang-format off
  32. static struct option opts[] = {
  33. {"mode", required_argument, NULL, 'm'},
  34. {0, 0, 0, 0},
  35. };
  36. // clang-format on
  37. // Need + as first character to get POSIX-style option parsing
  38. for(int c = -1; (c = getopt_long(argc, argv, "+:m:", opts, NULL)) != -1;)
  39. #else
  40. for(int c = -1; (c = getopt_nolong(argc, argv, ":m:")) != -1;)
  41. #endif
  42. {
  43. switch(c)
  44. {
  45. case 'm':
  46. mode = new_mode(optarg, 0666, &errstr);
  47. if(errstr != NULL)
  48. {
  49. fprintf(stderr, "mkfifo: error: Failed parsing mode '%s': %s\n", optarg, errstr);
  50. return 1;
  51. }
  52. break;
  53. case ':':
  54. fprintf(stderr, "mkfifo: error: Missing operand for option: '-%c'\n", optopt);
  55. usage();
  56. return 1;
  57. case '?':
  58. GETOPT_UNKNOWN_OPT
  59. usage();
  60. return 1;
  61. default:
  62. abort();
  63. }
  64. }
  65. argc -= optind;
  66. argv += optind;
  67. if(argc < 1)
  68. {
  69. fprintf(stderr, "mkfifo: error: Missing file argument\n");
  70. usage();
  71. return 1;
  72. }
  73. for(int i = 0; i < argc; i++)
  74. {
  75. if(mkfifo(argv[i], mode) != 0)
  76. {
  77. fprintf(
  78. stderr, "mkfifo: error: Failed creating FIFO at '%s': %s\n", argv[i], strerror(errno));
  79. return 1;
  80. }
  81. }
  82. return 0;
  83. }