vfork – the Faster fork
August 25, 2011 at 3:08 pm Leave a comment
I came across an interesting alternative for the good old fork: vfork.
Lets see a simple process creating example:
#include <stdio.h>
int main()
{
switch (fork())
{
case -1:
printf("Failed to create new process\n");
return -1;
case 0:
printf("Child running\n");
execvp(.. load child ...)
break;
default:
printf("Parent running\n");
wait();
break;
}
return 0;
}
This is the most common process creating pattern. Now what does fork do? It creates a child as an exact parent copy, with the same file descriptors, same stack, same stack and data segments. But most of the times, immediately after fork, the child will load a new image: its own code. So why do we need all the exact fork does?
For child processes that need to start as fast as possible, the solution is vfork: it creates the child without copying the parent segments. So faster. But safer?.. The trick here is that using vfork the child will share the file descriptors, the data, stack and text with the parent until it will load its own image. So any changes in the child will imediately affect the parent.
Here’s a short example:
#include <stdio.h>
int a = 1;
int main()
{
switch (vfork())
{
case -1:
printf("Failed to create new process\n");
return -1;
case 0:
printf("Child running\n");
a = 2 *a;
execvp(... child...);
break;
default:
sleep(1);
printf("Parent running - %d\n", a);
wait();
break;
}
return 0;
}
The output:
Child running
Parent running - 2
So use it, but use it wisely!
Entry filed under: Uncategorized. Tags: .
Trackback this post | Subscribe to the comments via RSS Feed