Skip to content

Instantly share code, notes, and snippets.

@fcharlie
Created August 29, 2017 08:34
Show Gist options
  • Save fcharlie/63beb90dfb106ce0299f4cdf00181343 to your computer and use it in GitHub Desktop.
Save fcharlie/63beb90dfb106ce0299f4cdf00181343 to your computer and use it in GitHub Desktop.
Server restart get other process command line for linux
#include <string>
#include <climits>
#include <cstring>
#include <unistd.h>
#include <vector>
#include <fcntl.h>
//// Support Restart
class ProcessArgv {
public:
ProcessArgv() = default;
ProcessArgv(const ProcessArgv &) = delete;
ProcessArgv &operator=(const ProcessArgv &) = delete;
~ProcessArgv() {
if (Argv_) {
free(Argv_);
}
if (Args) {
free(Args);
}
}
bool Initialize(int pid);
char **Argv() { return Argv_; }
size_t Argc() const { return Argc_; }
const std::string &AbsolutePath() const { return absolutePath; }
private:
std::string absolutePath;
char **Argv_{nullptr};
char *Args{nullptr};
size_t Argc_{0};
};
bool ProcessArgv::Initialize(int pid) {
absolutePath.resize(PATH_MAX);
auto N = readlink("/proc/self/exe", &absolutePath[0], PATH_MAX);
if (N <= 0) {
return false;
}
char filename[32];
snprintf(filename, sizeof(filename), "/proc/%d/cmdline", pid);
auto fd = open(filename, O_RDONLY);
if (fd <= 0) {
perror("cannot open /proc/pid/cmdline");
return false;
}
Args = (char *)malloc(sizeof(char) * PATH_MAX);
if (Args == nullptr) {
perror("malloc error");
close(fd);
return false;
}
auto ret = read(fd, Args, PATH_MAX);
std::vector<char *> Argvv;
Argvv.push_back(Args);
for (auto i = 0; i < ret; i++) {
if (Args[i] == 0 && i + 1 < ret) {
Argvv.push_back(&Args[++i]);
}
}
Argvv.push_back(nullptr);
close(fd);
size_t i = 0;
Argv_ = (char **)malloc(sizeof(char *) * (Argvv.size() + 1));
for (auto &p : Argvv) {
Argv_[i++] = p;
}
Argc_ = Argvv.size() - 1;
return true;
}
int main() {
/* code */
auto pid = getpid();
ProcessArgv argvX;
if (argvX.Initialize(pid)) {
fprintf(stderr, "Path %s\n", argvX.AbsolutePath().c_str());
for (size_t i = 0; i < argvX.Argc(); i++) {
fprintf(stderr, "%zu %s\n", i, argvX.Argv()[i]);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment