Forking in UNIX/Linux/OS X
Here is some code to fork a new process in UNIX and similar operating systems. Note: Forking is not most efficient method for multiprogramming because it is inefficient, but it is easy. The problem with forking is that it copies the whole address space of the parent process before resuming execution. In most cases people want to execute another program after forking. When an exec (or some variant of exec) is called, the first thing that happens is the address space of that process is wiped out and the new program is loaded into that address space. This is very inefficient because the kernel has to do all of this for the processes. If you don't want to copy the whole address space, check out the
vfork()command. Here is the code anyways.
#include <stdio.h>
#include <unistd.h>
int main(void)
{
pid_t pid;
int wait_for_child = 1;
int exec_res;
int value = 1;
char* command = "/bin/ls";
char* command_name = "ls";
// Fork new process, copies address space of parent
// process so static data, stack and heap are not shared.
// See
pid = fork();
// Both child and parent processes start here after the
// fork is called
if (pid == 0)
{
// Increment value in childs address space
value++;
// This is the child process
printf("I am the child. [%i]\n", value);
exec_res = execlp(command, command_name, NULL);
// Need to exit on error
if (!exec_res)
{
printf("Error. Could not exec.");
}
// Exit child process
exit(0);
}
else if (pid > 0)
{
// wait_for_child if exec is synchronous
if (wait_for_child)
{
printf("Wait for child to finish before resuming.\n");
wait(NULL);
}
printf("I am the parent. My child is %i. [%i]\n", pid, value);
}
else
{
printf("Error. Could not fork.");
}
return 1;
}
0 Comments:
Post a Comment
<< Home