Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling execv after creating a thread

I'm very new to threads, processes, execv, etc. I have researched and found that when you execute an execv, it takes the space of the calling process. I am wondering what happens when you create a thread in main, and then call execv, directly after the thread (not before it finishes but right after the thread is created). I know execv will replace main but does this mean that it will also replace the thread or will the thread be able to execute and complete like normal?

Small example of what I'm asking:

  int main(){
      printf("hello from main!);
      char *buffer = "some data";

    if(pthread_creat(&mythreadpid, NULL, thread1, buffer){
        printf("ERROR!!");
     }

     execv(...) //do execv here

}

void *thread1(void *buffer){
  printf("calling from my thread!");

 //do something else

}

I have tested this and I did experience strange behavior as my thread wouldn't complete so I want to know if this is the reason for it

like image 648
unconditionalcoder Avatar asked Mar 11 '23 19:03

unconditionalcoder


1 Answers

All the exec functions replace the entire process with the program being executed. All threads are destroyed.

If you want to execute another program without affecting the current process, you should use fork() first to create a new process, and call execv() in the child process. See Is it safe to fork from within a thread? for some caveats to be aware of when using fork() in a multi-threaded program.

like image 71
Barmar Avatar answered Mar 20 '23 08:03

Barmar