C++在shell中使用计时器执行多个命令

标签 c++ linux bash shell

在同一个 shell 中执行多个 shell 命令并在一个命令和另一个命令之间有延迟的最佳方法是什么?

例如,这是在不同的 shell 中执行 cdls 命令的示例代码。如何添加 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 库调用的手册页( execlforkwait )和上面的 sleep_for 链接。和 chrono .

关于C++在shell中使用计时器执行多个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44028713/

相关文章:

用于防止多个 JVM 进程多次写入的 Java Filelock 不起作用

linux - Bash 陷阱从函数中取消设置

Bash 脚本检查 cmd 的输出是否在一段时间内增加,如果是则运行

bash - 有没有办法在 ubuntu 18 的 crontab 作业脚本中使用 .envrc

c++ - 限制 C++ 中的递归调用(大约 5000 次)?

c++ - 为什么这会被转换为 int?

c++ - FreeRTOS 仅在发布时崩溃

linux - 通过 USB 进行 NXC 通信

c++ - 在 cpp 文件中使用内联命名空间的类型在 MSVS 中不起作用

linux - Bash 脚本 - Grep/Awk 输出作为另一个脚本的输入