when call fork(), OS create a new process.
the two process is all same, and return from fork() function.
but according the man fork()
, when it create success.
call wait() to delay its execution, until target proccess is completed
wait for any child process
wait(NULL) will block parent process until any of its children has finished
wait for all child process completed
POSIX defines a function: wait(NULL);. It‘s the shorthand for waitpid(-1, NULL, 0);
while ((wpid = wait(&status)) > 0);
work with fork()
the exec family function will replace the current processs image with new process image.
so the rest codes of original process, will not execution.
execvp
The first argument, by convention, should point to the file name associated with the file being exe-cuted. The list of arguments must be terminated by a NULL pointer.
the separation of fork() and exec() is essential in building a UNIX shell
cmd: fork ------------------------ -> wait -> output
\ -> pre-env -> exec -> exit /
Specifically, UNIX systems start looking for free file descriptors at zero. In this case, STDOUT FILENO will be the first available one and thus get assigned when open() is called. Subsequent writes by the child process to the standard output file descriptor, for example by routines such as printf(), will then be routed transpar- ently to the newly-opened file instead of the screen.
The process 1, and PID=1
the very first process (called init) is started by the kernel at booting time and never terminates
A child that terminates, but has not been waited for becomes a "zombie".
running process whose parent process has finished or terminated
In most cases, the new parent is the
init
process, one with the PID 1.
is an intintionally orphaned process
A daemon process is usually created by a process forking a child process and then immediately exiting, thus causing init to adopt the child process. In a Unix environment, the parent process of a daemon is often, but not always, the init process.
原文:https://www.cnblogs.com/Gilfoyle/p/15227380.html