Decoded: mkdir (coreutils)

[Back to Project Main Page]

Note: This page explores the design of command-line utilities. It is not a user guide.
[GNU Manual] [POSIX requirement] [Linux man] [FreeBSD man]

Logical flow of mkdir command (coreutils)

Summary

mkdir - make directories

[Source] [Code Walkthrough]

Lines of code: 297
Principal syscall: mkdir()
Support syscalls: None
Options: 10 (4 short, 6 long)

Descended from mkdir introduced in Version 1 UNIX (1971)
Added to Fileutils in October 1992 [First version]
Number of revisions: 156 [Code Evolution]

Helpers:
  • announce_mkdir() - Prints directory creation results (if -v used)
  • make_ancestor() - Function to create the requested ancestor and return result
  • process_dir() - Wrapper for make_dir_parents() to handle security context
External non-standard helpers:
  • die() - Exit with mandatory non-zero error and message to stderr
  • error() - Outputs error message to standard error with possible process termination
  • make_dir_parents() - gnulib function to prepare inputs for mkdir()
  • savewd_process_files() - Processes the input files using process_dir() (gnulib)

Setup

mkdir employs a struct mkdir_options to hold data for the operating behavior. The key elements include a function pointer for creating ancestors, several mode_t permission masks, security context usage, and a display format.

mkdir initializes local variables in main(), including:

  • mkdir_options - Options struct for this execution
  • optc - The next option to process
  • *scontext - The user specified security context
  • *specified_mode - A file mode as input by the user

Parsing

Parsing mkdir considers four questions:

  • What are the permissions of the new directory?
  • Do ancestor directories need to be created?
  • Are there security considerations? (SELinux / Smack)
  • Should the user get verbose feedback for all created directories?

Parsing failures

These failure cases are explicitly checked:

  • Security context provided without a compliant kernel
  • No target operand provided

Failures result in a short error message followed by the usage instructions.


Execution

The mkdir utility ultimate passes collected user information to gnulib for directory creation. However, there are some tasks to perform first:

  • Verify the security context for directory creation
  • Pass the creation functions and option values to gnulib (via savewd_process_files())
  • In gnulib:
    • Process all ancestors if requested
    • Create the final target directory
  • Return exit status (any failure forces EXIT_FAILURE)

Failure cases:

  • Unable to set creation context
  • Unknown mode specified
  • gnulib functions fail fur any reason

All failures at this stage output an error message to STDERR and return without displaying usage help


[Back to Project Main Page]