1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Linux][C/C++] pid, ppid, tidを取得する方法まとめ

Posted at

Linux, pidで検索してもBashでの方法ばかりでるので、C/C++での方法のまとめ

使用するAPI

pid => getpid()

Man page of GETPID

ppid => getppid()

Man page of GETPID

tid => syscall(SYS_getid)

Man page of GETTID

※注意 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

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?