Last active
March 15, 2020 01:43
-
-
Save pedrominicz/60fb07c13a6f80fc54af8431db54e602 to your computer and use it in GitHub Desktop.
`fork` and `exec` in C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/wait.h> | |
#include <unistd.h> | |
#include <stdarg.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
// This function is taken from `http://git.suckless.org/dwm/file/util.c.html`. | |
// | |
// Print the error message and `perror` if the message ends in `':'`. Assumes | |
// `fmt` is not `NULL`. | |
void die(const char* fmt, ...) { | |
va_list ap; | |
va_start(ap, fmt); | |
vfprintf(stderr, fmt, ap); | |
va_end(ap); | |
// Following Unix convention (see `man perror`), first check if the string is | |
// not empty. | |
if(fmt[0] && fmt[strlen(fmt) - 1] == ':') { | |
fputc(' ', stderr); | |
perror(NULL); | |
} else { | |
fputc('\n', stderr); | |
} | |
exit(0); | |
} | |
int main(int argc, char** argv) { | |
// `fork` current process. On success, the child's PID is returned to the | |
// parent and `0` is returned to the child. On failure, `-1` is returned and | |
// no process is created. | |
pid_t pid = fork(); | |
if(pid == -1) die("could not fork:"); | |
// At this point there are two processes running. The parent will not enter | |
// the `if` statement and the child will. | |
if(pid == 0) { | |
// In the `exec` family of functions, functions with `l` are variadic (i.e. | |
// take `argv` in multiple arguments) and functions with `p` search for the | |
// executable file in the `PATH` environment variable. | |
// | |
// Note that `'echo'` is repeated twice because the first one refers to the | |
// process to execute and the second one to the first argument passed to | |
// the process, i.e. `argv[0]`. | |
// | |
// Since only the child enters the `if` statement, only the child becomes | |
// an `echo` process. | |
execlp("echo", "echo", "hello world", NULL); | |
} | |
// Suspend the execution of the parent until one of its children terminates. | |
// In this case, the only child is bound to execute `echo`. | |
wait(NULL); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment