使用两个线程和 system() 命令到 运行 shell 脚本:如何确保一个 shell 脚本在另一个之前启动
Using two threads and system() command to run shell scripts: how to make sure that one shell script is started before another
有两个 shell 脚本:
#shell_script_1
nc -l -p 2234
#shell_script_2
echo "hello" | nc -p 1234 localhost 2234 -w0
从 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();
}
当我 运行 上面的程序时,shell_script_1 运行s 在 shell_script_2 之前,正如预期的那样。但是,5 秒的等待是否足以确保两个 shell 脚本按顺序启动?无论如何,除了设置计时器和交叉我的手指之外,我可以执行命令吗?谢谢。
将第一个脚本 "start" 放在第二个脚本之前是不够的。您希望第一个脚本实际侦听您指定的端口。为此,您需要定期检查。这将取决于平台,但在 Linux 上,您可以检查第一个 child 的 /proc/PID
以了解它打开了哪些文件描述符,and/or 运行 nc -z
检查端口是否正在监听。
一种更简单的方法是,如果第二个脚本无法连接并且第一个线程仍处于 运行ning 状态,则自动重试几次第二个脚本。
一种更复杂的方法是让您的 C++ 程序绑定两个端口并在两个端口上侦听,然后将您的第一个脚本更改为连接而不是侦听。这样两个脚本都将充当客户端,而您的 C++ 启动器将充当服务器(即使它所做的只是在两个 children 之间传递数据),让您有更多的控制权并避免竞争。
有两个 shell 脚本:
#shell_script_1
nc -l -p 2234
#shell_script_2
echo "hello" | nc -p 1234 localhost 2234 -w0
从 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();
}
当我 运行 上面的程序时,shell_script_1 运行s 在 shell_script_2 之前,正如预期的那样。但是,5 秒的等待是否足以确保两个 shell 脚本按顺序启动?无论如何,除了设置计时器和交叉我的手指之外,我可以执行命令吗?谢谢。
将第一个脚本 "start" 放在第二个脚本之前是不够的。您希望第一个脚本实际侦听您指定的端口。为此,您需要定期检查。这将取决于平台,但在 Linux 上,您可以检查第一个 child 的 /proc/PID
以了解它打开了哪些文件描述符,and/or 运行 nc -z
检查端口是否正在监听。
一种更简单的方法是,如果第二个脚本无法连接并且第一个线程仍处于 运行ning 状态,则自动重试几次第二个脚本。
一种更复杂的方法是让您的 C++ 程序绑定两个端口并在两个端口上侦听,然后将您的第一个脚本更改为连接而不是侦听。这样两个脚本都将充当客户端,而您的 C++ 启动器将充当服务器(即使它所做的只是在两个 children 之间传递数据),让您有更多的控制权并避免竞争。