Linux, pidで検索してもBashでの方法ばかりでるので、C/C++での方法のまとめ
使用するAPI
pid => getpid()
ppid => getppid()
tid => syscall(SYS_getid)
※注意 pthread_self が返す値はLinuxのtidではない
Man page of PTHREAD_SELF
実装例
test.cpp
#include <iostream>
#include <future>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
pid_t gettid(void) {
return syscall(SYS_gettid);
}
int main() {
std::cout << "[0] pid : " << getpid() << std::endl;
std::cout << "[0] ppid : " << getppid() << std::endl;
std::cout << "[0] tid : " << gettid() << std::endl;
auto func = [] {
std::cout << "[1] pid : " << getpid() << std::endl;
std::cout << "[1] ppid : " << getppid() << std::endl;
std::cout << "[1] tid : " << gettid() << std::endl;
};
auto th = std::thread(func);
th.join();
return 0;
}
実行結果
$ g++ -pthread -std=gnu++11 test.cpp && ./a.out
[0] pid : 13762
[0] ppid : 9459
[0] tid : 13762
[1] pid : 13762
[1] ppid : 9459
[1] tid : 13763
関連
[Linux][C/C++] tid (thread id) を取得する / pthread_createをラップして子スレッドのtidの取得 - Qiita