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 *.
A calculator child program adapted for use with the Windows spawn functions.
calculator.c56 lines
/* * 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;}
Editing — changes sent to terminal on Run
$ 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.c126 lines
/* * main.c — Windows _spawnl/_spawnlp/_spawnv process creation * * Key concepts: _spawnl, _spawnlp, _spawnv (Windows-only, not POSIX) * Compile: cl main.c (MSVC only) * Run: ./prog */#include <stdio.h>#include <stdlib.h>#include <process.h> // For spawn functionsint main(){ printf("\n"); printf("══════════════════════════════════════\n"); printf(" Windows _spawnl/_spawnlp/_spawnv process creation\n"); printf("══════════════════════════════════════\n\n"); printf("\n"); printf(" It won't compile on Linux/macOS.\n"); printf(" Linux equivalent: fork() + exec()\n\n"); const int EXAMPLE = 2; printf("[Parent] Running _spawn example %d...\n\n", EXAMPLE); if (EXAMPLE == 1) { // Example 1: Using _spawnl printf("Launching calculator using _spawnl...\n"); int status = spawnl(_P_WAIT, "./calculator.exe", "calculator", "5", "+", "3", NULL); // the are spawn flags: // _P_WAIT: Wait for the spawned process to finish // _P_NOWAIT: Don't wait for the spawned process to finish // _P_DETACH: Detach the spawned process, basicly making it independent from the parent process, without any connection if (status == -1) { perror("spawnl failed"); } else { printf("Calculator finished with status: %d\n", status); } } else if (EXAMPLE == 2) { // Example 2: Using spawnv printf("Launching calculator using _spawnv...\n"); //char *args[] = {"calculator.exe", "8", "X", "4", NULL}; ///////////////// IMPORTANT NOTE ////////////////// //the problem is, when we pass * as an argv to the child process, it will be interpreted as a wildcard // which means, it will be replaced by the shell with all the files in the current directory // so i had this BUG for two days, and didnt understand why is the child process got like 8 arguments //so the fix is just to pass a X instead of a * (or any other token than *), and it will work // we can also use //* instead of * to escape the wildcard // or use #define _CRT_glob 0 to disable the wildcard expansion char *args[] = {"calculator", "8", "*", "4", NULL}; int status = spawnv(_P_WAIT, "./calculator.exe", args); printf("Arguments being passed to _spawnv:\n"); for (int i = 0; args[i] != NULL; i++) { printf("args[%d]: %s\n", i, args[i]); } // SPAWNV inject environment variables to the child process // now we have explicity disabled the environment variables // which means, we cant see the child output, because we didnt pass the environment variables // which one of them is stdout // so the best solution is just to use spawnl //testinbg spawnvp // int status = spawnvp(_P_WAIT, "./calculator.exe", args); if (status == -1) { perror("spawnv failed"); } else { printf("Calculator finished with status: %d\n", status); } } else if (EXAMPLE == 3) { // in order to fix example 2, to stop injecting , we can use spawnv // but we pass an empty environment array, so still we wont be able to see the child output printf("Launching calculator using _spawnve with custom environment...\n"); // Correct args array char *args[] = {"calculator.exe", "8", "*", "4", NULL}; // Minimal environment char *env[] = {NULL}; // No inherited environment variables // Debug: Print arguments being passed to _spawnve printf("Arguments being passed to _spawnve:\n"); for (int i = 0; args[i] != NULL; i++) { printf("args[%d]: %s\n", i, args[i]); } // Launch the child process with a minimal environment int status = spawnve(_P_WAIT, "./calculator.exe", args, env); if (status == -1) { printf("spawnve failed\n"); perror("spawnve failed"); } else { printf("Calculator finished with status: %d\n", status); } printf("Parent continues without waiting. Child launched with status: %d\n", status); } else { fprintf(stderr, "Invalid example selected\n"); } return 0;}
Editing — changes sent to terminal on Run
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.c61 lines
/* * 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 childstatic 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;}
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.c70 lines
/* * 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;}
Editing — changes sent to terminal on Run
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.c20 lines
/* * 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;}
Editing — changes sent to terminal on Run
$ 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.c40 lines
/* * 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;}
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.c44 lines
/* * 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;}