Understanding how the child process executes in this code
I was given this starter code for a project, but am having difficulty understanding how the child process executes.
int pid ;
int child_info = -1;
if ( argv[0] == NULL ) /* nothing succeeds */
return 0;
if( (pid= fork()==-1)
perror("fork");
else if 开发者_运维技巧( pid == 0 ){
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
execvp(argv[0], argv);
perror("cannot execute command");
exit(1);
}
else { //check if wait error or print out exit status
if ( wait(&child_info) == -1 )
perror("wait");
else {
printf("Exit status: %d, %d\n", child_info>>8, child_info&0377);
}
}
return child_info;
}
Looking at the code, the current process forks and in this case, the child inherits all of the relevant properties of the parent process, since there are no timers, signals or anything involved. However, the pid values of the new processes are in the 18000 range, so how can execvp(argv[0], argv)
be executed since in this case, pid != 0.
From the fine manual for fork
:
Upon successful completion, fork() shall return 0 to the child process and shall return the process ID of the child process to the parent process.
The first branch of the if
is an error condition and will be executed in the parent process if there was an error. The second branch (pid == 0
) is executed in the child process, the child does a bit of signal housekeeping and does the exec
. The third branch is in the parent when there was no error.
In the parent, pid
will be non-zero but in the new child process, pid
will be zero.
It gets executed in the child process, where pid will be 0. http://linux.die.net/man/2/fork
Fork returns the pid of the child to the parent process and 0 to the child process. so when asking for pid == 0
means "is this the child process?". If so, it executes the program passed through command line arguments.
There's only one new process created; the child.
fork()
in the child process returns 0
, which is what you're checking for.
fork()
in the parent process (your original process) returns the child process' pid.
By checking the return of fork()
for 0
you know if you're the parent or child; you're the child if it's 0
.
精彩评论