Skip to content

Instantly share code, notes, and snippets.

@bnoordhuis
Created August 4, 2011 23:37
Show Gist options
  • Save bnoordhuis/1126584 to your computer and use it in GitHub Desktop.
Save bnoordhuis/1126584 to your computer and use it in GitHub Desktop.
fork vs vfork
/*
* Copyright (c) 2011, Ben Noordhuis <info@bnoordhuis.nl>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE /* pipe2 */
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/wait.h>
#ifdef __linux__
#include <linux/version.h>
/* pipe2() requires linux >= 2.6.27 and glibc >= 2.9 */
#define HAVE_PIPE2 \
defined(LINUX_VERSION_CODE) && defined(__GLIBC_PREREQ) && LINUX_VERSION_CODE >= 0x2061B && __GLIBC_PREREQ(2, 9))
#endif
#define assert_errno() \
do { \
if (errno != 0) { \
fprintf(stderr, \
"%s:%d: %s\n", \
__FILE__, \
__LINE__, \
strerror(errno)); \
abort(); \
} \
} \
while (0);
#define E(expr) (expr); assert_errno();
int main(int argc, char **argv) {
int status;
pid_t pid;
int i;
(void) argc;
if (argv[1])
return 42;
for (i = 0; i < 10e3; i++) {
#ifdef VFORK
E(pid = vfork());
#else
E(pid = fork());
#endif
if (pid) {
E(waitpid(pid, &status, 0));
assert(WIFEXITED(status));
assert(WEXITSTATUS(status) == 42);
}
else {
char *argp[] = { argv[0], ".", NULL };
char *envp[] = { NULL };
execve(argv[0], argp, envp);
_exit(127);
}
}
return 0;
}
$ time ./fork
real 0m6.694s
user 0m0.000s
sys 0m0.760s
$ time ./fork
real 0m6.834s
user 0m0.030s
sys 0m0.750s
$ time ./fork
real 0m6.872s
user 0m0.050s
sys 0m0.750s
$ time ./fork
real 0m5.006s
user 0m0.000s
sys 0m0.300s
$ time ./fork
real 0m5.590s
user 0m0.000s
sys 0m0.330s
$ time ./fork
real 0m5.332s
user 0m0.020s
sys 0m0.290s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment