背景
最近在使用pgrep获取进程id的,出现了一个奇怪的现象,获取不到进程的id信息,但是使用ps查看,进程的确存在,如下所示,为什么会出现这样的一种情况呢?
#ps aux | grep main
root 62221 0.0 0.0 6392 384 pts/4 S+ 14:47 0:00 ./main
#pgrep -x main
无输出
问题分析
通过ps看进程名字也能对的上,pgrep main如下也有输出,那这么看就是 -x(精确匹配)导致不生效了。
#pgrep main
62221
pidstat查看进程详细的线程信息,如下发现主线程的名字和进程名不一样,难道pgrep查找的不是进程名,而是主线程名。
02:56:08 PM UID TGID TID %usr %system %guest %CPU CPU Command
02:56:09 PM 0 32018 - 0.00 0.00 0.00 0.00 33 main_process
02:56:09 PM 0 - 32018 0.00 0.00 0.00 0.00 33 |__main_process
然后执行 pgrep -x main_process 发现有输出,基本可以得出结论,pgrep和主线程名相关,和进程名字无关。
附测试代码
#include <stdio.h>
#include <pthread.h>
int main()
{
pthread_t id = pthread_self();
pthread_setname_np(id, "main_process");
while (1) {
sleep(1);
}
return 0;
}