[英]How to execute shell commands and interact with the output on linux using C++?
[英]C++ execute multiple commands with timer in 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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.