The operating system must provide a mechanism to create and manipulate processes.
One paradigm might be:
process_id = create_process("name", arguments);
Another paradigm, used under Unix, has two primitives:
Make a twin copy of the existing process with the fork() operation.
Replace this twin with the new process with the exec() operation.
The first paradigm is simpler to use and understand.
Unix uses the second paradigm in order to flexibly determine what system resources the new process inherits.
Under Unix, the new process is called the child process.
Unix uses the two primitives fork and exec in the following manner:
/* Given the arguments in argv, fork a * child and execute the new program. * Returns when the child dies. */ int execute(argv) char *argv[];{ int pid; /* Holds the process-id of the child */
switch (pid = fork()) /* Call fork, and test what it returns */ { case -1: printf("The fork failed\n"); return (-1);
case 0: /* The child is given a value of 0 from fork() */ /* Do special things like closing files etc. */
/* Replace ourselves with the real child */ /* Call execvp */ execvp(argv[0],argv); exit(1); /* Exec failed, indicate error */
default: /* The parent receives the new process-id from fork() */ wait(); /* Wait for child to exit */ }
fork() creates a new process, by making copies of the old process' code, data and stack.
Both continue execution by getting a value back from fork() -- the child gets 0, and the parent get the child's process-id.
exec() replaces a running process with a new process, with new code, data and stack. The process-id remains the same.
Note that fork() by itself is useless, and so it exec().
Redirection in Unix is achieved after the fork() (when the twin is created), but before the exec(). Thus, the new process is oblivious to where its standard I/O is coming from.
Every process calls exit() when they finish, to inform the parent that it has terminated, and how.
If the parent process wait()s, it is blocked until the child dies, and it received the child's exit status.
Finally kill(pid) can be used to kill a process. Of course the OS prevents you from killing a process you didn't create.
forked: [UNIX; prob. influenced by a mainstream expletive] adj. Terminally slow, or dead. Originated when one system slowed to incredibly bad speeds because of a process recursively spawning copies of itself (using the UNIX system call fork()) and taking up all the process table entries.