如何在 bash 上同时 运行 2 个命令

How to run 2 commands on bash concurrently

我想测试我刚做的服务器程序(姑且称之为A)。所以当A被这个命令执行时

$VALGRIND ./test/server_tests 2 >>./test/test.log

,无法侦听 connection.After,我想使用

连接到 A 中的服务器
nc 127.0.0.1 1234 < ./test/server_file.txt

所以A可以解封继续。问题是我必须在两个不同的终端中手动键入这些命令,因为它们都会阻塞。我还没有找到在单个 shell 脚本中自动执行此操作的方法。任何帮助将不胜感激。

您可以使用 & 在后台 运行 进程并继续使用相同的 shell。

$VALGRIND ./test/server_tests 2 >>./test/test.log &
nc 127.0.0.1 1234 < ./test/server_file.txt

如果您希望服务器在您关闭终端后继续 运行ning,您可以使用 nohup:

nohup $VALGRIND ./test/server_tests 2 >>./test/test.log &
nc 127.0.0.1 1234 < ./test/server_file.txt

进一步参考:https://www.computerhope.com/unix/unohup.htm

从问题来看,如果目标是为服务器构建一个测试脚本,那也会捕获内存检查。

对于构建测试脚本的特定情况,扩展评论中引用的问题并添加一些命令以使测试脚本不太可能挂起是有意义的。脚本会限制执行客户端、执行服务器的时间,如果测试提前完成,它会尝试关闭服务器。

   # Put the server to the background
(timeout 15 $VALGRIND ./test/server_tests 2 >>./test/test.log0 &
svc_pid=$!

   # run the test cilent
timeout 5 nc 127.0.0.1 1234 < ./test/server_file.txt
   .. Additional tests here

   # Terminate the server, if still running. May use other commands/signals, based on server.
kill -0 $svc_id && kill $svc_pid
wait $svc_pid

   # Check log file for error
   ...