Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 146 ยท Standard Library and Foundation

Processes and Environment

Learn how a Swift program talks to its surroundings - command-line arguments, environment variables, ProcessInfo, exit codes, stderr, and running other programs with Process and Pipe.

A program does not live alone. It is started by someone (a shell, a build system, a scheduler), with a list of arguments, a set of environment variables and a place to send its output. When it ends, it hands back an exit code that tells its caller whether it worked. Command-line tools, scripts, servers and test runners all depend on these conventions, and Swift programs follow them like any other.

This lesson covers CommandLine and ProcessInfo for reading arguments and the environment, exit and standard error for reporting results, and Process and Pipe for starting other programs from Swift. It builds on reading input and files. A good many of these examples depend on the machine they run on, so the code prints only facts that are true everywhere.

In the runner on this site your program starts with no arguments and a minimal environment, and the process is named binary. Everything below also works on your own computer; there you pass arguments after the program name (swift run tool --name Ada, or ./tool --name Ada).

Command-line arguments

CommandLine.arguments is an array of strings. The first element, at index 0, is how the program was invoked (its path); the rest are the arguments, in order. ProcessInfo.processInfo.arguments returns the same array.

Swift Reading the arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

With no arguments the array holds one element (the program itself), the user part is empty, and the program prints no --name given. The loop above has a bug waiting to happen: if a user passes --name as the last argument, flags.index(after:) points past the end and the program traps. Real argument parsing must handle missing values. The cleanest way is to write the parser as a function that takes an array, so you can test it with any input, not only the real arguments:

Swift A small testable argument parser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first sample gives the defaults, the second fills in all fields (name: "Ada", count: 3, verbose: true, files: ["a.txt", "b.txt"]), and the three bad samples produce missingValue("--name"), invalidNumber("many") and unknownFlag("--colour"). The last two lines run the same parser on the real arguments. Notice case let flag where flag.hasPrefix("-") in the switch: it catches every unknown option before the default case treats the argument as a file name.

For serious command-line tools, use the Swift Argument Parser package. It generates parsing, help text and error messages from a struct. It is a third-party package, so it cannot run in this sandbox, but the hand-written version above shows what it does for you.

Environment variables

The environment is a dictionary of strings that a program inherits from whatever started it. It carries things such as PATH (where to look for programs), HOME, and configuration like LOG_LEVEL or DATABASE_URL. Environment variables are the standard way to configure programs in containers and in cloud hosting, because you can change them without touching the code or the files.

Swift Reading and changing environment variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

environment is a [String: String], so a missing variable is nil and ?? supplies a default: here info. The PORT check shows the careful pattern for numbers: variables are always strings, and they may be missing or invalid, so convert with Int(...) and fall back. setenv changes the environment of the running process (the third argument 1 means overwrite), getenv reads it through the C interface, and unsetenv removes it again. Children started later inherit these changes.

Never print or log the whole environment. It often holds secrets such as API keys and database passwords. Read the one variable you need, and treat its value as sensitive.

What the system tells you

ProcessInfo also describes the process and the machine:

Swift Facts from ProcessInfo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The process is called binary here, and all the Bool lines print the facts that hold on any machine; the real values (memory size, processor count, uptime) differ between computers, which is why the lesson does not print them. The #if os(...) lines are compile-time conditions: the compiler keeps only the branch for the platform being built, which is how one code base supports several systems.

Not every API exists on every platform. ProcessInfo on Apple systems has thermalState and isLowPowerModeEnabled; the Linux Foundation does not. The compiler tells you at build time:

Swift An Apple-only property (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

TEXT
main.swift:2:31: error: value of type 'ProcessInfo' has no member 'isLowPowerModeEnabled'

Guard platform-specific code with #if os(iOS) || os(macOS) (or #if canImport(...)) so the rest of the program still builds elsewhere.

Exit codes and standard error

When a program finishes, it returns an exit code, an integer from 0 to 255. By universal convention 0 means success and anything else means failure; the caller (a shell script, a CI job, make) uses it to decide what to do. A program that returns the end of main.swift exits with 0. To exit earlier, or with a failure code, call exit(_:).

Human-readable errors belong on standard error (stderr), not standard output, so that output a user pipes into another program stays clean.

Swift Exit with a failure code (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output shows working..., the message under stderr, and a note that the program ended with exit code 3. exit has the return type Never, which tells the compiler that nothing after it can run (see assertions and preconditions).

There is one trap. exit ends the process immediately and does not run defer blocks or deinitializers of live objects. If you have cleanup to do, do it before calling exit, or register it with atexit:

Swift exit skips defer, but not atexit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see working, defer inside work (the function returned normally), about to exit and atexit handler ran. The top-level defer is skipped because exit leaves without unwinding the scope. This is also the quiet way a Swift program can fail to flush its own buffers or remove a lock file: structure main.swift so the real work is in a function that returns a code, and call exit once at the very end.

A crash is also an exit: fatalError prints a message and the file and line, then the process dies with a signal.

Swift fatalError (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is start, then binary/main.swift:2: Fatal error: no config found on stderr, a backtrace, and the process is killed with SIGILL. A signal-ended process has no regular exit code; shells report 128 + signal number. Use fatalError for "this can never happen" states, and exit with a meaningful code for expected failures such as bad input.

Running other programs with Process

Process (formerly NSTask) starts another program, optionally wiring its input and output to your code with Pipe. This is how you call git, ffmpeg or a shell script from Swift. It is available in Foundation on Linux and macOS, but not on iOS. The sandbox here allows it for programs that exist in the container, such as /bin/echo, /bin/sh and /bin/cat.

The safe pattern is a small helper that takes the program path and an array of arguments and returns the exit status and both output streams:

Swift A helper that runs a program and captures its output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first call returns CommandResult(status: 0, output: "one two\n", errors: ""). The shell call sees only the two variables we gave it (environment: replaces the inherited environment), prints hi, swift, writes oops to stderr and exits with status 2, and the three prints show out: hi, swift, err: oops and status: 2. The tr program reads the text we write to its standard input and prints SHOUT THIS. The last two calls show a program that produces 20,000 lines (the count comes back as 20000) and a program that does not exist, where run() throws a "file not found" error.

Several details make this helper reliable:

  • Pass arguments as an array, never as one string. Each element reaches the program untouched, with no shell in between. If you build "echo " + userText and give it to sh -c, a text like x; rm -rf ~ becomes a second command. That is command injection, one of the most common security holes. With an argument array, the text is just data.
  • Close the child's input when you are done writing, or a program such as cat or tr will wait forever for more.
  • Read the output before waitUntilExit(). A pipe holds only about 64 KB. If the child writes more while you are waiting for it to finish, both sides block forever (a deadlock). readDataToEndOfFile() drains the pipe until the child closes it.
  • Check terminationStatus. Zero means success; for a program killed by a signal, the status is the signal number and terminationReason is .uncaughtSignal.

You can also stop a program that runs too long:

Swift Terminating a child process

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The 30-second sleep is stopped at once: running: true, then running: false, killed by signal: true and the signal number 15 (SIGTERM). terminate() sends a polite stop request; a stubborn program may need a second step such as kill. In real tools, start a timer task that calls terminate() after a deadline, as shown in cancellation and timeouts.

Standard input

Your program can also receive data on standard input, typically from a pipe or a file redirect. readLine() returns the next line, or nil at the end of the input. In this sandbox any readLine() example must preset input in the TryIt; with nothing supplied, the first call returns an empty string and the second one returns nil. The input lesson covers it fully.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is CommandLine.arguments[0]?

    Index 0 is the program path; the user's arguments start at index 1, so use dropFirst().
  2. 2. What type does ProcessInfo.processInfo.environment["PORT"] have?

    Environment variables are strings, and the key may be missing, so you convert with Int(...) and provide a default.
  3. 3. What happens to defer blocks when you call exit(0)?

    exit does not unwind scopes. Do cleanup first, or use atexit.
  4. 4. Why should you pass program arguments to Process as an array instead of building a shell command string?

    With sh -c and a concatenated string, user text can add extra commands. With an argument array no shell parses it.
  5. 5. A child process writes 1 MB to its output pipe. What is the safe way to read it?

    A pipe buffers about 64 KB. If nobody reads, the child blocks and waitUntilExit() never returns.

Summary

  • CommandLine.arguments (same as ProcessInfo.processInfo.arguments) starts with the program itself; user arguments follow. Write the parser as a function of [String] so you can test it, and handle missing values.
  • ProcessInfo.processInfo.environment is a [String: String]; use ?? and Int(...) for defaults and conversions, and never log the whole environment.
  • setenv, getenv and unsetenv change the environment of the running process and its future children.
  • Exit code 0 is success. Write errors to FileHandle.standardError and finish with exit(code); exit skips defer, and fatalError ends the program with a signal.
  • Platform-specific APIs need #if os(...) guards; some ProcessInfo properties exist only on Apple systems.
  • Process plus Pipe runs other programs: pass an argument array, close the child's input, read output before waiting, and check terminationStatus.

Next: Networking with URLSession shows how Swift programs talk over the network, and what can and cannot run in the sandbox.