在同一个 shell 中执行多个 shell 命令并在一个命令和另一个命令之间有延迟的最佳方法是什么?
例如,这是在不同的 shell 中执行 cd
和 ls
命令的示例代码。如何添加 10 秒延迟并在同一个 shell 中运行它们?也许用usleep
?
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <cerrno>
#include <unistd.h>
#include <chrono>
#include <thread>
int main() {
system("gnome-terminal -x sh -c 'cd; ls; exec bash'");
return 0;
}
最佳答案
您可以使用 std::this_thread::sleep_for
.
你应该使用 fork
+ exec*
(+ wait
) 而不是 system
: system
容易受到别名的影响,您无法用它很好地处理错误。
编辑
例子:
#include <unistd.h>
#include <thread>
#include <chrono>
//Function made in less than 5 minute
// You should improve it (error handling, ...)
// I use variadic template to be able to give a non fixed
// number of parameters
template<typename... str>
void my_system(str... p) {
// Fork create a new process
switch fork() {
case 0: // we are in the new process
execl(p..., (char*)nullptr); // execl execute the executable passed in parameter
break;
case -1: // Fork returned an error
exit(1);
default: // We are in the parent process
wait(); // We wait for the child process to end
break;
}
}
int main() {
using namespace std::chrono_literals;
// start a command
my_system(<executable path>, "cd") ;
// sleep for 2 second
std::this_thread::sleep_for(2s);
// ....
my_system(<executable path>, "ls") ;
std::this_thread::sleep_for(2s);
my_system(<executable path>, "exec", "bash") ;
std::this_thread::sleep_for(2s);
}
警告 此代码未经测试,请勿进行任何错误处理,可能存在错误!我会让你修理它。查看 posix 库调用的手册页( execl
、 fork
、 wait
)和上面的 sleep_for
链接。和 chrono
.
关于C++在shell中使用计时器执行多个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44028713/