Created
June 11, 2019 12:17
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstdlib> | |
#include <cstdio> | |
#include <string> | |
std::string exec_cmd(std::string cmd) { | |
if (cmd.empty()) { | |
return ""; | |
} | |
std::cout <<cmd <<std::endl; | |
auto cmd_pipe = popen(cmd.c_str(), "r"); | |
if (nullptr == cmd_pipe) { | |
return ""; | |
} | |
char line_str[64] = ""; | |
if (nullptr == fgets(line_str, sizeof(line_str), cmd_pipe)) { | |
pclose(cmd_pipe); | |
return ""; | |
} | |
pclose(cmd_pipe); | |
return line_str; | |
} | |
pid_t get_process_id(std::string proc_name) { | |
if (proc_name.empty()) { | |
return -1; | |
} | |
int base = 10; | |
std::string cmd = std::string("pidof -s ") + proc_name; | |
auto line_str = exec_cmd(cmd); | |
if (line_str.empty()) { | |
return -1; | |
} | |
return strtoul(line_str.c_str(), nullptr, base); | |
} | |
bool process_started(std::string proc_name) { | |
auto pid = get_process_id(proc_name); | |
std::cout <<"pid:" <<pid <<std::endl; | |
return !(pid < 0); | |
} | |
int main(int argc, char **argv) { | |
if (argc != 2) { | |
std::cout <<"usage: " <<argv[0] <<" programe" <<std::endl; | |
return -1; | |
} | |
std::string prog = argv[1]; | |
if (process_started(prog)) { | |
std::cout <<prog <<" started!" <<std::endl; | |
} else { | |
std::cout <<prog <<" not started!" <<std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment