0

I've been trying to launch and close an external program at certain point during my code, and was relying on system() calls to accomplish that. However, here it was suggested that I use execlp and a separate std::thread entirely, in order to suppress console outputs.

The problem is, both of these solutions imply waiting for the program to close, which I want to avoid, as I need to communicate with that program (right now through UNIX sockets). Is there any way to use either execlp or std::thread to lauch a program in background, as I do with system([program]&)?

Community
  • 1
  • 1
joaocandre
  • 1,621
  • 4
  • 25
  • 42
  • 2
    When you use the `exec` family of functions, you can't use threads. You have to create a completely new process using the `fork` system call. – Some programmer dude Jul 23 '13 at 10:45
  • 2
    As for how to do it, there are many, **many**, examples all over the Internet. A simple search in your favorite search engine will find you hundreds of examples. – Some programmer dude Jul 23 '13 at 10:46

1 Answers1

1

actually you can use threads :) but with care... the simplest way to do fork before spawning any thread in parent/all process/es. then, after fork you may start any needed threads (anywhere you want: in parent as well as in child process).

doing fork there is no threads started automatically in a child process, but I suppose you don't need them... child usually do some preparations and exec required process, so you don't need to respawn any threads in it. (anyway if you want, you can do it!). then, you have to watch your child via waitpid and wait for it's death.

PS: also read man pthread_atfork if you really need some threads in a child.

zaufi
  • 6,811
  • 26
  • 34