c++ - I'm confused how this execvp() is handled in this sample function which uses fork() to clone a process -


i have following function book titled "advanced linux programming".

int spawn (char* program, char** arg_list) {     pid_t child_pid;      /* duplicate process. */     child_pid = fork ();      if (child_pid != 0)     /* parent process. */     return child_pid;      else {     /* execute program, searching in path. */     execvp (program, arg_list);      /* execvp function returns if error occurs. */     fprintf (stderr, “an error occurred in execvp\n”);     abort ();     } } 

but i'm confused that, in cases ls executed successfully, error not printed, in case fails, prints error put in line following it.

my question line fprintf (stderr, “an error occurred in execvp\n”); after execvp() function, , expected executed after execution of execvp() finishes, not case, , executed if execvp() encounters error. seems function spawn() finishes executes execvp() successfully. right?

you can have @ manpage execvp, says:

the exec() family of functions replaces current process image new process image.

so, mean? means, if execvp succeeds, program wont in memory anymore, wont ever reach error message. program in memory replaced new program (in case ls if understood correctly).

so, if program able reach error message printout, execvp function have failed. otherwise other program starts execution.

the reason why programm still running fork command, creates copy of process image, having 2 same processes running of 1 replaced command try execute. achieved if clause if (child_pid != 0), fork command duplicate process , return new process id (pid). if set 0 (see man 3 fork), new child process, if != 0 parent process. function there executes execvp if child process, parent process encounters return.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -