c++ - 使用两个线程和system()命令运行shell脚本: how to make sure that one shell script is started before another

标签 c++ multithreading c++11 pthreads

有两个 shell 脚本:

#shell_script_1
nc -l -p 2234

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

从 C++ 程序内部,我想首先运行 shell 脚本 no.1,然后运行 ​​shell script no.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();

}

当我运行上面的程序时,shell_script_1 在 shell_script_2 之前运行,正如预期的那样。然而,5 秒的等待是否足以确保两个 shell 脚本按顺序启动?除了设置计时器并祈祷之外,我还能强制执行该命令吗?谢谢。

最佳答案

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

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

更复杂的方法是让您的 C++ 程序绑定(bind)两个端口并监听两个端口,然后将第一个脚本更改为连接而不是监听。这样,两个脚本都将充当客户端,而您的 C++ 启动器将充当服务器(即使它所做的只是在两个子脚本之间传递数据),从而为您提供更多控制并避免竞争。

关于c++ - 使用两个线程和system()命令运行shell脚本: how to make sure that one shell script is started before another,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59434602/

相关文章:

c++ - 一个简单的 boost.spirit 示例中的 error_invalid_expression 编译错误

java - 多线程 + RxJava 条件观察

c# - BackgroundWorker.CancellationPending 线程安全如何?

c++ - 传递具有模板化返回类型的 std::function 类型

c++ - 我可以在 C++ 中移动临时对象的属性吗?

c++ - 在编译时在 C++ 中生成随机数

c# - 在 C++ 应用程序的另一个目录中使用 C# 库

c++ - 问题理解 shared_ptr

c++ - 使用线程传递指针时出错

java - 类条件的等待方法不抛出 InterruptedException