4
6

More than 5 years have passed since last update.

C/C++で実行時に自身のプロセス名を取得する (Linux向け)

Last updated at Posted at 2016-05-16

C, C++ で実行時に自身のプロセス名を取得する方法まとめ

get_process_name.cpp
#include <iostream>
#include <cstdlib>
#include <errno.h>

extern char *__progname;

int main(int argc, char const* argv[])
{
        // argv[0]
        std::cout << "argv[0] : " << argv[0] << std::endl;

        // linux environment
        std::cout << "getenv(\"_\") : " << getenv("_") << std::endl;

        // libc
        std::cout << "__progname : " << __progname << std::endl;

        // errno.h
        std::cout << "program_invocation_name : " << program_invocation_name << std::endl;
        std::cout << "program_invocation_short_name : " << program_invocation_short_name << std::endl;

        return 0;
}
実行例
/tmp$ g++ get_process_name.cpp -o hoge && ./hoge
argv[0] : ./hoge
getenv("_") : ./hoge
__progname : hoge
program_invocation_name : ./hoge
program_invocation_short_name : hoge

/tmp$ g++ get_process_name.cpp -o hoge && $PWD/hoge
argv[0] : /tmp/hoge
getenv("_") : /tmp/hoge
__progname : hoge
program_invocation_name : /tmp/hoge
program_invocation_short_name : hoge

参考

c - How to get current process name in linux? - Stack Overflow

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6