简体   繁体   English

c + +与壳计时器执行多条命令

[英]C++ execute multiple commands with timer in shell

what is the best way to execute multiple shell commands with a delay between one and another in the same shell? 什么是一个又一个在同一个外壳之间的延迟执行多个shell命令的最佳方式?

Eg, this is a sample code that executes cd and ls commands but in different shells. 例如,这是执行一个示例代码cdls命令,但在不同的壳。 How can I add a 10 seconds delay and running them in the same shell? 如何添加10秒的延迟,并在同一个shell中运行呢? Maybe with usleep ? 也许有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;
}

You can use std::this_thread::sleep_for . 您可以使用std::this_thread::sleep_for

You should use fork + exec* (+ wait ) instead of system : system is vulnerable to alias and you can't handle well error with it. 您应该使用fork + exec* (+ wait )而不是systemsystem容易受到别名的影响,因此无法很好地处理错误。

EDIT 编辑

Example: 例:

#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);
}

WARNING this code was not tested, do not do any error handling and may have bugs ! 警告:此代码并没有进行测试,没有做任何的错误处理,并可能有错误! I will let you fix it. 我会让你修复它。 Check the man page for the call to the posix library ( execl , fork , wait ) and the above link for sleep_for and chrono . 检查手册页调用POSIX库( execlforkwait )和上面的链接sleep_forchrono

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM