Lesson 05intermediateProcesses

Process Spawning: Windows and Linux

Spawning a program in one call. Read the Windows versions (_spawnl, _spawnlp, _spawnv with _P_WAIT/_P_NOWAIT, and the argv quirks with spaces and *), then run the Linux counterpart posix_spawn — and see that on Linux it is the shell, not spawn, that splits words and expands *.

spawnposix_spawnWindowsargvshell
1

Calculator for Spawn

A calculator child program adapted for use with the Windows spawn functions.

calculator.c
/*
 * calculator.c — Calculator for Windows spawn examples
 *
 * Key concepts: Simple calculator, used as child process by main.c
 * Compile: gcc -o calculator calculator.c
 * Run:     ./prog
 */
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Calculator for Windows spawn examples\n");
    printf("══════════════════════════════════════\n\n");
    printf("\n");
    if (argc != 4) {
        //recived the following arguments:
        printf("argc in calculator: %d\n", argc);
        for (int i = 0; i < argc; i++) {
            printf("argv[%d]: %s\n", i, argv[i]);
        }
        fprintf(stderr, "Usage: %s <num1> <operator> <num2>\n", argv[0]);
        return 1;
    }

    int num1 = atoi(argv[1]);
    char operator = argv[2][0];
    int num2 = atoi(argv[3]);
    int result;

    
    switch (operator) {
        case '+': result = num1 + num2; break;
        case '-': result = num1 - num2; break;
       // the * is a "wildcard" in the shell, so we cant use it as an argument
       // case '*': result = num1 * num2; break;
        case 'X': result = num1 * num2; break;
        case '/': 
            if (num2 == 0) {
                fprintf(stderr, "Error: Division by zero\n");
                return 1;
            }
            result = num1 / num2; 
            break;
        default:
            fprintf(stderr, "Error: Unknown operator '%c'\n", operator);
            return 1;
    }

    printf("[Calculator] %d %c %d = %d\n", num1, operator, num2, result);
    printf("\n========================================\n");
    return 0;
}
$ gcc -o calculator calculator.c
$ ./calculator 6 + 7
Expected Outputclick Run to execute live
══════════════════════════════════════
  Calculator for Windows spawn examples
══════════════════════════════════════


[Calculator] 6 + 7 = 13

========================================
2

Spawn Variants

Using _spawnl, _spawnlp, and _spawnv to create child processes on Windows — analogous to fork+exec on Linux.

main.c
Windows only — read alongUses process.h / _spawn — read along. The next example, 01-posix-spawn.c, is the runnable Linux version.
3

posix_spawn: the Linux Spawn

The runnable counterpart of the Windows example above: posix_spawn runs the calculator and waits right away (like _P_WAIT) or keeps working and waits later (like _P_NOWAIT) — then the parent's line and the child's result can appear in either order. posix_spawnp searches PATH like _spawnlp.

01-posix-spawn.c
/*
 * 01-posix-spawn.c — The Linux "spawn": fork + exec in one call (compare main.c on Windows)
 *
 * Key concepts: posix_spawn / posix_spawnp, waitpid right away (like _P_WAIT) or later (_P_NOWAIT)
 * Compile: gcc -o calculator calculator.c && gcc -o posix_spawn 01-posix-spawn.c
 * Run:     ./posix_spawn
 *
 *   Windows (main.c)                      Linux (this file)
 *   _spawnl(_P_WAIT, "./calculator", …)   posix_spawn(&pid, "./calculator", …) + waitpid(pid)
 *   _spawnlp(…, "calculator", …)          posix_spawnp: searches PATH, like execvp
 *   _P_NOWAIT                             posix_spawn, do other work, waitpid later
 *
 * posix_spawn takes an argv ARRAY (there is no "l" list form) and returns 0 or an error number.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <spawn.h>
#include <unistd.h>
#include <sys/wait.h>

extern char **environ;                    // pass our environment on to the child

static pid_t spawn_calc(char *a, char *op, char *b)
{
    char *argv[] = { "calculator", a, op, b, NULL };
    pid_t pid;
    int err = posix_spawn(&pid, "./calculator", NULL, NULL, argv, environ);
    if (err != 0) {                       // returns the error number itself (not -1/errno)
        fprintf(stderr, "posix_spawn: %s\n", strerror(err));
        exit(EXIT_FAILURE);
    }
    return pid;
}

int main(void)
{
    int status;

    printf("1) Spawn and wait right away (like _P_WAIT):\n");
    fflush(stdout);
    pid_t pid = spawn_calc("5", "+", "3");
    waitpid(pid, &status, 0);
    printf("   -> calculator exited with status %d\n\n", WEXITSTATUS(status));

    printf("2) Spawn, keep working, wait later (like _P_NOWAIT):\n");
    fflush(stdout);
    pid = spawn_calc("8", "X", "4");
    printf("   [Parent] spawned PID %d and kept going without waiting\n", pid);
    fflush(stdout);
    waitpid(pid, &status, 0);
    printf("   -> collected it later, status %d\n\n", WEXITSTATUS(status));

    printf("3) posix_spawnp searches PATH (like _spawnlp / execvp):\n");
    fflush(stdout);
    char *argv[] = { "echo", "   hello from echo, found via PATH", NULL };
    if (posix_spawnp(&pid, "echo", NULL, NULL, argv, environ) == 0)
        waitpid(pid, &status, 0);
    return EXIT_SUCCESS;
}
$ gcc -o calculator calculator.c && gcc -o posix_spawn 01-posix-spawn.c
$ ./posix_spawn
Expected Outputclick Run to execute live
1) Spawn and wait right away (like _P_WAIT):

══════════════════════════════════════
  Calculator for Windows spawn examples
══════════════════════════════════════


[Calculator] 5 + 3 = 8

========================================
   -> calculator exited with status 0

2) Spawn, keep working, wait later (like _P_NOWAIT):
   [Parent] spawned PID 1280 and kept going without waiting

══════════════════════════════════════
  Calculator for Windows spawn examples
══════════════════════════════════════


[Calculator] 8 X 4 = 32

========================================
   -> collected it later, status 0

3) posix_spawnp searches PATH (like _spawnlp / execvp):
   hello from echo, found via PATH
4

Windows argv Parsing Quirks

Demonstrating surprising Windows behavior when argv values contain spaces or special characters.

weird_behaviours/shell.c
/*
 * shell.c — Windows shell argv parsing quirks
 *
 * Key concepts: Windows command line parsing, argv escaping edge cases
 * Compile: cl shell.c (MSVC only)
 * Run:     ./prog
 */

#include <process.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Windows shell argv parsing quirks\n");
    printf("══════════════════════════════════════\n\n");
    printf("\n");
    char program_name[100];
    char input_string[100];


    ////// this example is to recreate wierd C windows run time behaviours
    // using spawn
    //// if we pass a string like "aa bb cc" as an argument to the program
    // without the quotes, the spawn function, and the c windows run time, will separate the string
    // into 3 different argv arguments so: aa, bb, cc
    // but we we pass the string with quotes, the spawn function will pass the string as a single argument
    // try for yourself, run the program first and enter the following:
    // program name: ./unique_str
    // input string: aa bb cc      - without qutoes

    // than run it again and enter the following:
    // program name: ./unique_str
    // input string: "aa bb cc"    - with quotes

    // Get the name of the program to run
    printf("Enter the program name to run (e.g., unique_str): ");
    fflush(stdout);
    scanf("%99s", program_name);

    // Get the input string
    printf("Enter the string to pass as a single argument (e.g., \"aa bb cc\"): ");
    fflush(stdout);
    getchar(); // Consume the newline left in the buffer
    fgets(input_string, sizeof(input_string), stdin);

    // Remove newline character if present
    size_t len = strlen(input_string);
    if (len > 0 && input_string[len - 1] == '\n') {
        input_string[len - 1] = '\0';
    }
    printf("[Shell] Received input: \"%s\"\n", input_string);
    printf("[Shell] Spawning %s with this as a single argument...\n\n", program_name);
    // Arguments for spawn
    char *args[] = {program_name, input_string, NULL};

    // Spawn the program with _P_WAIT so the parent waits for the child to complete
    int status = spawnv(_P_WAIT, program_name, args);
    if (status == -1) {
        perror("spawnv failed");
        return 1;
    } else {
        printf("[Shell] Child finished with exit status: %d\n\n", status);
    }

    return 0;
}
Windows only — read alongUses process.h — Windows only. 02-args-shell-vs-spawn.c shows where these quirks come from on Linux.
5

What Did the Program Receive?

A helper that prints each argument in brackets, so spaces become visible: [two words] is one argument. The quotes in the run command keep "two words" and "*" intact.

show_args.c
/*
 * show_args.c — Print exactly the arguments this program received
 *
 * Key concepts: argc/argv as the child sees them (a helper for 02-args-shell-vs-spawn.c)
 * Compile: gcc -o show_args show_args.c
 * Run:     ./show_args one "two words" "*"
 *
 * Brackets make spaces visible: [two words] is ONE argument.
 */
#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("    show_args got argc=%d:", argc - 1);
    for (int i = 1; i < argc; i++)
        printf(" [%s]", argv[i]);
    printf("\n");
    return 0;
}
$ gcc -o show_args show_args.c
$ ./show_args one "two words" "*"
Expected Outputclick Run to execute live
    show_args got argc=3: [one] [two words] [*]
6

Who Splits Words and Expands *?

posix_spawn hands {"aa bb cc", "*"} over intact (2 arguments). system() goes through /bin/sh, which splits the words and replaces * with every file name in the folder — suddenly many arguments: the bug from the Windows example, explained. Quoting fixes it.

02-args-shell-vs-spawn.c
/*
 * 02-args-shell-vs-spawn.c — Who splits "aa bb cc" and who expands * ? (the Windows quirks, on Linux)
 *
 * Key concepts: argv passes through spawn/exec untouched; the SHELL splits words and expands *
 * Compile: gcc -o show_args show_args.c && gcc -o args_demo 02-args-shell-vs-spawn.c
 * Run:     ./args_demo
 *
 * On Windows the program gets ONE command-line string and its C runtime re-splits it and
 * expands * (that was the "two days" bug in main.c). On Linux the argv array arrives exactly
 * as passed — splitting and * expansion happen only when a SHELL reads a command line,
 * for example through system().
 */
#include <stdio.h>
#include <stdlib.h>
#include <spawn.h>
#include <sys/wait.h>

extern char **environ;

int main(void)
{
    char *argv[] = { "show_args", "aa bb cc", "*", NULL };
    pid_t pid;
    int status;

    printf("1) posix_spawn with the array {\"aa bb cc\", \"*\"} — no shell involved:\n");
    fflush(stdout);
    posix_spawn(&pid, "./show_args", NULL, NULL, argv, environ);
    waitpid(pid, &status, 0);

    printf("\n2) system(\"./show_args aa bb cc *\") — /bin/sh reads it as a command line:\n");
    fflush(stdout);
    system("./show_args aa bb cc *");     // split into words, and * becomes the file names here

    printf("\n3) Same through the shell, but quoted:\n");
    fflush(stdout);
    system("./show_args \"aa bb cc\" '*'");
    return EXIT_SUCCESS;
}
$ gcc -o show_args show_args.c && gcc -o args_demo 02-args-shell-vs-spawn.c
$ ./args_demo
Expected Outputclick Run to execute live
1) posix_spawn with the array {"aa bb cc", "*"} — no shell involved:
    show_args got argc=2: [aa bb cc] [*]

2) system("./show_args aa bb cc *") — /bin/sh reads it as a command line:
    show_args got argc=7: [aa] [bb] [cc] [02-args-shell-vs-spawn.c] [args_demo] [show_args] [show_args.c]

3) Same through the shell, but quoted:
    show_args got argc=2: [aa bb cc] [*]
7

Spawn with Output to a File

posix_spawn_file_actions_addopen opens result.txt as the child's stdout before the calculator starts — the spawn version of fork + dup2 + exec from Lesson 04. Open result.txt in the Files panel.

03-spawn-redirect.c
/*
 * 03-spawn-redirect.c — Spawn with the child's output going to a file
 *
 * Key concepts: posix_spawn_file_actions_addopen — the spawn version of fork + dup2 + exec (Lesson 04)
 * Compile: gcc -o calculator calculator.c && gcc -o spawn_redirect 03-spawn-redirect.c
 * Run:     ./spawn_redirect       (then open result.txt in the Files panel)
 *
 * With fork you would open() + dup2() in the child before exec. posix_spawn cannot run your code
 * in the child, so you describe the plan instead: "open result.txt as file descriptor 1 first".
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <spawn.h>
#include <unistd.h>
#include <sys/wait.h>

extern char **environ;

int main(void)
{
    posix_spawn_file_actions_t actions;
    posix_spawn_file_actions_init(&actions);
    // In the child, before the program starts: open result.txt AS stdout (fd 1)
    posix_spawn_file_actions_addopen(&actions, STDOUT_FILENO, "result.txt",
                                     O_WRONLY | O_CREAT | O_TRUNC, 0644);

    char *argv[] = { "calculator", "6", "X", "7", NULL };
    pid_t pid;
    int err = posix_spawn(&pid, "./calculator", &actions, NULL, argv, environ);
    posix_spawn_file_actions_destroy(&actions);
    if (err != 0) {
        fprintf(stderr, "posix_spawn: %s\n", strerror(err));
        return EXIT_FAILURE;
    }

    int status;
    waitpid(pid, &status, 0);
    printf("[Parent] calculator (PID %d) exited with %d; everything it printed is in result.txt.\n",
           pid, WEXITSTATUS(status));
    return EXIT_SUCCESS;
}
$ gcc -o calculator calculator.c && gcc -o spawn_redirect 03-spawn-redirect.c
$ ./spawn_redirect
Expected Outputclick Run to execute live
[Parent] calculator (PID 1345) exited with 0; everything it printed is in result.txt.
8

String Uniqueness Check

A small utility to check if all characters in a string are unique.

weird_behaviours/unique_str.c
/*
 * unique_str.c — String uniqueness check (utility)
 *
 * Key concepts: character counting, duplicate detection
 * Compile: gcc -o unique unique_str.c
 * Run:     ./prog
 */
#include <stdio.h>

int main(int argc, char *argv[]) {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  String uniqueness check (utility)\n");
    printf("══════════════════════════════════════\n\n");
    printf("\n");
    printf("[unique_str] Received %d argument(s):\n\n", argc);
    printf("  %-8s | %s\n", "Index", "Value");
    printf("  -------- | -----\n");
    for (int i = 0; i < argc; i++) {
        printf("  argv[%d]  | \"%s\"\n", i, argv[i]);
    }
    printf("\n");
    if (argc == 2) {
        printf("  String was passed as a SINGLE argument (correct)\n");
    } else if (argc > 2) {
        printf("  String was SPLIT into %d args (Windows shell quirk!)\n", argc - 1);
    }
    printf("\n========================================\n");
    return 0;
} 
$ gcc -o unique_str weird_behaviours/unique_str.c
$ ./unique_str
Expected Outputclick Run to execute live
══════════════════════════════════════
  String uniqueness check (utility)
══════════════════════════════════════


[unique_str] Received 1 argument(s):

  Index    | Value
  -------- | -----
  argv[0]  | "./unique_str"


========================================

Open Full Terminal

Get a Linux terminal with all 8 files from this lesson pre-loaded. Compile, run, and experiment freely.