C++ 使用两个线程和system()命令运行shell脚本:如何确保一个shell脚本在另一个shell脚本之前启动

C++ 使用两个线程和system()命令运行shell脚本:如何确保一个shell脚本在另一个shell脚本之前启动,c++,multithreading,c++11,pthreads,C++,Multithreading,C++11,Pthreads,有两个shell脚本: #shell_script_1 nc -l -p 2234 从C++程序内部开始,首先运行shell脚本1,然后运行shell脚本2。我现在拥有的是这样的东西: #include <string> #include <thread> #include <cstdlib> #include <unistd.h> int main() { std::string sh_1 = "./shell_script_1";

有两个shell脚本:

#shell_script_1
nc -l -p 2234


从C++程序内部开始,首先运行shell脚本1,然后运行shell脚本2。我现在拥有的是这样的东西:

#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();

}
#包括
#包括
#包括
#包括
int main()
{
std::string sh_1=“./shell_脚本_1”;
std::string sh_2=“./shell_脚本_2”;
std::线程t1(&system,sh_1.c_str());
usleep(5000000);//等待5秒
std::线程t2(&system,sh_2.c_str());
t1.join();
t2.连接();
}
当我运行上面的程序时,正如预期的那样,shell_script_1在shell_script_2之前运行。但是,5秒钟的等待是否足以确保两个shell脚本按顺序启动?除了设置计时器和交叉手指,我还能执行命令吗?谢谢

在第二个脚本之前“启动”第一个脚本是不够的。您希望第一个脚本实际正在您指定的端口上侦听。要做到这一点,您需要定期检查。这取决于平台,但在Linux上,您可以检查第一个子级的
/proc/PID
,以了解它打开了哪些文件描述符,和/或运行
nc-z
以检查端口是否正在侦听

一种更简单的方法是,如果第二个脚本无法连接并且第一个线程仍在运行,则自动重试第二个脚本几次


<> P>一种更复杂的方法是让C++程序绑定两个端口并同时侦听两个端口,并将第一个脚本更改为连接而不是侦听。这样,两个脚本都可以充当客户端,而C++启动程序将充当服务器(即使它所做的只是在两个孩子之间传递数据),从而给予您更多的控制和避免种族。

提出的更复杂的方法在某些方面肯定更干净,但第二个更简单。这种方法是在不同机器上运行的客户机和服务器如何协调事情的最佳模型。
#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();

}