【问题标题】:C++ execute multiple commands with timer in shellC ++在shell中使用计时器执行多个命令
【发布时间】:2017-05-17 15:10:39
【问题描述】:

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

例如,这是一个执行 cdls 命令但在不同 shell 中的示例代码。如何添加 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;
}

【问题讨论】:

  • system() 很糟糕,原因有很多(例如安全漏洞、对正在运行的程序缺乏控制等等),忘记它的存在并永远使用它。

标签: c++ linux bash shell


【解决方案1】:

您可以使用std::this_thread::sleep_for

你应该使用fork + exec* (+ wait) 而不是systemsystem 容易受到别名的影响,你不能用它处理好错误。

编辑

例子:

#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_forchrono 的链接。

【讨论】:

  • 你能告诉我如何使用我的部分代码来写你所说的吗?谢谢:)
  • 我添加了一个示例。不要简单地复制/粘贴我的示例,因为它没有经过测试(这意味着它可能有错误)并且没有错误处理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多