Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After execvp returns, why doesn't my program pick up where it left off?

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?

like image 418
samoz Avatar asked Dec 22 '22 12:12

samoz


2 Answers

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.

like image 142
Johannes Schaub - litb Avatar answered May 12 '23 22:05

Johannes Schaub - litb


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.

like image 27
aib Avatar answered May 12 '23 22:05

aib