views:

194

answers:

3

I have a block of code like this that runs as a child thread:

if(someVar == 1){
doSomeStuff;

_exit(0)
}
else
   execvp(*(temp->_arguments), temp->_arguments);
printf("I'm done\n");

When I run the program with someVar == 1, I understand that the _exit(0) call kills my thread. However, when it's set to 0, why doesn't the program continue after the execvp() call and do the printf statement?

+1  A: 

execvp() overwrites your program with the new executable and doesn't return, unless an error occurs. You need to fork() first and then call exec* on the child process.

aib
A: 

because execvp replaces the process you were running with the process you exec'ed. If execvp returns, it's because it failed. It shouldn't return otherwise.

Nathan Fellman
+6  A: 

If you exec* (call any exec function from the exec family), then the code of a new program is loaded into your current process and execution continues with its main function and its stuff. On a successful execution of those functions, they will never return because your printf does not exist anymore in memory.

I think you confuse exec* with the fork function. That will splice off a new child process which will run the same code as the parent.

If what you want is to create a new thread, that shares data and the address space with the main thread, you should use the pthread_create function. A new process will not share data and you will have to communicate with the other process using other mechanisms, like pipes or shared memory.

Johannes Schaub - litb