samedi 21 décembre 2019

Using two threads and system() command to run shell scripts: how to make sure that one shell script is started before another

There are two shell scripts:

#shell_script_1
nc -l -p 2234

#shell_script_2
echo "hello" | nc -p 1234 localhost 2234 -w0  

From inside the C++ program, I want to run shell script no.1 first, and then run shell script no.2. What I have now is something like this:

#include <string>
#include <thread>
#include <cstdlib>
#include <unistd.h>

int main()
{
  std::string sh_1 = "./shell_script_1";
  std::string sh_2 = "./shell_script_2";

  std::thread t1( &system, sh_1.c_str() );

  usleep( 5000000 ); //wait for 5 seconds

  std::thread t2( &system, sh_2.c_str() );

  t1.join();
  t2.join();

}

When I run the program above, shell_script_1 runs before shell_script_2, as expected. However, is a 5-second wait enough to make sure that the two shell scripts start in order? Is there anyway I can enforce the order other than set a timer and cross my finger? Thanks.

Aucun commentaire:

Enregistrer un commentaire