Java开源工具在linux上的源码分析(二):信号处理

开发 后端
当java虚拟机启动的时候,会启动很多内部的线程,这些线程主要在thread.cpp里的create_vm方法体里实现。而在thread.cpp里主要起了2个线程来处理信号相关的。详细请看下文

当java虚拟机启动的时候,会启动很多内部的线程,这些线程主要在thread.cpp里的create_vm方法体里实现。

而在thread.cpp里主要起了2个线程来处理信号相关的:

  1. JvmtiExport::enter_live_phase();  
  2.  
  3. // Signal Dispatcher needs to be started before VMInit event is posted  
  4. os::signal_init();  
  5.  
  6. // Start Attach Listener if +StartAttachListener or it can't be started lazily  
  7. if (!DisableAttachMechanism) {  
  8.   if (StartAttachListener || AttachListener::init_at_startup()) {  
  9.     AttachListener::init();  
  10.   }  

1. Signal Dispatcher 线程

在os.cpp中的signal_init()函数中,启动了signal dispatcher 线程,对signal dispather 线程主要是用于处理信号,等待信号并且分发处理,可以详细看signal_thread_entry的方法:

  1. static void signal_thread_entry(JavaThread* thread, TRAPS) {  
  2.   os::set_priority(thread, NearMaxPriority);  
  3.   while (true) {  
  4.     int sig;  
  5.     {  
  6.       // FIXME : Currently we have not decieded what should be the status  
  7.       //         for this java thread blocked here. Once we decide about  
  8.       //         that we should fix this.  
  9.       sig = os::signal_wait();  
  10.     }  
  11.     if (sig == os::sigexitnum_pd()) {  
  12.        // Terminate the signal thread  
  13.        return;  
  14.     }  
  15.  
  16.     switch (sig) {  
  17.       case SIGBREAK: {  
  18.         // Check if the signal is a trigger to start the Attach Listener - in that  
  19.         // case don't print stack traces.  
  20.         if (!DisableAttachMechanism && AttachListener::is_init_trigger()) {  
  21.           continue;  
  22.         }  
  23.         // Print stack traces  
  24.         // Any SIGBREAK operations added here should make sure to flush  
  25.         // the output stream (e.g. tty->flush()) after output.  See 4803766.  
  26.         // Each module also prints an extra carriage return after its output.  
  27.         VM_PrintThreads op;  
  28.         VMThread::execute(&op);  
  29.         VM_PrintJNI jni_op;  
  30.         VMThread::execute(&jni_op);  
  31.         VM_FindDeadlocks op1(tty);  
  32.         VMThread::execute(&op1);  
  33.         Universe::print_heap_at_SIGBREAK();  
  34.         if (PrintClassHistogram) {  
  35.           VM_GC_HeapInspection op1(gclog_or_tty, true /* force full GC before heap inspection */,  
  36.                                    true /* need_prologue */);  
  37.           VMThread::execute(&op1);  
  38.         }  
  39.         if (JvmtiExport::should_post_data_dump()) {  
  40.           JvmtiExport::post_data_dump();  
  41.         }  
  42.         break;  
  43.       }  
  44.       default: {  
  45.         // Dispatch the signal to java  
  46.         HandleMark hm(THREAD);  
  47.         klassOop k = SystemDictionary::resolve_or_null(vmSymbolHandles::sun_misc_Signal(), THREAD);  
  48.         KlassHandle klass (THREAD, k);  
  49.         if (klass.not_null()) {  
  50.           JavaValue result(T_VOID);  
  51.           JavaCallArguments args;  
  52.           args.push_int(sig);  
  53.           JavaCalls::call_static(  
  54.             &result,  
  55.             klass,  
  56.             vmSymbolHandles::dispatch_name(),  
  57.             vmSymbolHandles::int_void_signature(),  
  58.             &args,  
  59.             THREAD  
  60.           );  
  61.         }  
  62.         if (HAS_PENDING_EXCEPTION) {  
  63.           // tty is initialized early so we don't expect it to be null, but  
  64.           // if it is we can't risk doing an initialization that might  
  65.           // trigger additional out-of-memory conditions  
  66.           if (tty != NULL) {  
  67.             char klass_name[256];  
  68.             char tmp_sig_name[16];  
  69.             const char* sig_name = "UNKNOWN";  
  70.             instanceKlass::cast(PENDING_EXCEPTION->klass())->  
  71.               name()->as_klass_external_name(klass_name, 256);  
  72.             if (os::exception_name(sig, tmp_sig_name, 16) != NULL)  
  73.               sig_name = tmp_sig_name;  
  74.             warning("Exception %s occurred dispatching signal %s to handler" 
  75.                     "- the VM may need to be forcibly terminated",  
  76.                     klass_name, sig_name );  
  77.           }  
  78.           CLEAR_PENDING_EXCEPTION;  
  79.         }  
  80.       }  
  81.     }  
  82.   }  

可以看到通过os::signal_wait();等待信号,而在linux里是通过sem_wait()来实现,接受到SIGBREAK(linux 中的QUIT)信号的时候(关于信号处理请参考笔者的另一篇博客:java 中关于信号的处理在linux下的实现),***次通过调用 AttachListener::is_init_trigger()初始化attach listener线程,详细见2.Attach Listener 线程。

***次收到信号,会开始初始化,当初始化成功,将会直接返回,而且不返回任何线程stack的信息(通过socket file的操作返回),并且第二次将不在需要初始化。如果初始化不成功,将直接在控制台的outputstream中打印线程栈信息。
第二次收到信号,如果已经初始化过,将直接在控制台中打印线程的栈信息。如果没有初始化,继续初始化,走和***次相同的流程。

2. Attach Listener 线程

Attach Listener 线程是负责接收到外部的命令,而对该命令进行执行的并且吧结果返回给发送者。在jvm启动的时候,如果没有指定+StartAttachListener,该线程是不会启动的,刚才我们讨论到了在接受到quit信号之后,会调用 AttachListener::is_init_trigger()通过调用用AttachListener::init()启动了Attach Listener 线程,同时在不同的操作系统下初始化,在linux中 是在attachListener_Linux.cpp文件中实现的。

在linux中如果发现文件.attach_pid#pid存在,才会启动attach listener线程,同时初始化了socket 文件,也就是通常jmap,jstack tool干的事情,先创立attach_pid#pid文件,然后发quit信号,通过这种方式暗式的启动了Attach Listener线程(见博客:http://blog.csdn.net/raintungli/article/details/7023092)。

线程的实现在 attach_listener_thread_entry 方法体中实现:

  1. static void attach_listener_thread_entry(JavaThread* thread, TRAPS) {  
  2.   os::set_priority(thread, NearMaxPriority);  
  3.  
  4.   if (AttachListener::pd_init() != 0) {  
  5.     return;  
  6.   }  
  7.   AttachListener::set_initialized();  
  8.  
  9.   for (;;) {  
  10.     AttachOperation* op = AttachListener::dequeue();    
  11.      if (op == NULL) {  
  12.       return;   // dequeue failed or shutdown  
  13.     }  
  14.  
  15.     ResourceMark rm;  
  16.     bufferedStream st;  
  17.     jint res = JNI_OK;  
  18.  
  19.     // handle special detachall operation  
  20.     if (strcmp(op->name(), AttachOperation::detachall_operation_name()) == 0) {  
  21.       AttachListener::detachall();  
  22.     } else {  
  23.       // find the function to dispatch too  
  24.       AttachOperationFunctionInfo* info = NULL;  
  25.       for (int i=0; funcs[i].name != NULL; i++) {  
  26.         const char* name = funcs[i].name;  
  27.         assert(strlen(name) <= AttachOperation::name_length_max, "operation <= name_length_max");  
  28.         if (strcmp(op->name(), name) == 0) {  
  29.           info = &(funcs[i]);  
  30.           break;  
  31.         }  
  32.       }  
  33.  
  34.       // check for platform dependent attach operation  
  35.       if (info == NULL) {  
  36.         info = AttachListener::pd_find_operation(op->name());  
  37.       }  
  38.  
  39.       if (info != NULL) {  
  40.         // dispatch to the function that implements this operation  
  41.         res = (info->func)(op, &st);  
  42.       } else {  
  43.         st.print("Operation %s not recognized!", op->name());  
  44.         res = JNI_ERR;  
  45.       }  
  46.     }  
  47.  
  48.     // operation complete - send result and output to client  
  49.     op->complete(res, &st);  
  50.   }  

在AttachListener::dequeue(); 在liunx里的实现就是监听刚才创建的socket的文件,如果有请求进来,找到请求对应的操作,调用操作得到结果并把结果写到这个socket的文件,如果你把socket的文件删除,jstack/jmap会出现错误信息 unable to open socket file:........

 

我们经常使用 kill -3 pid的操作打印出线程栈信息,我们可以看到具体的实现是在Signal Dispatcher 线程中完成的,因为kill -3 pid 并不会创建.attach_pid#pid文件,所以一直初始化不成功,从而线程的栈信息被打印到控制台中。

原文链接:http://blog.csdn.net/raintungli/article/details/7034005

【系列文章】

  1. Java开源工具在linux上的源码分析(一):跟踪方式
  2. Java开源工具在linux上的源码分析(三):执行的线程vm thread
  3. Java开源工具在linux上的源码分析(四):safe point
  4. Java开源工具在linux上的源码分析(五):-F参数的bug
  5. Java开源工具在linux上的源码分析(六):符号表的读取
责任编辑:林师授 来源: raintungli的博客
相关推荐

2012-03-02 12:31:50

Javajmapjstack

2012-03-02 12:14:19

JavaJstackJmap

2012-03-02 12:25:07

Javajmapjstack

2012-03-02 12:38:49

Javajmapjstack

2012-03-02 13:29:38

Javajmapjstack

2022-06-26 18:09:43

Linux开源

2019-10-16 17:00:51

LinuxUbuntuVMware

2020-05-06 09:51:37

二进制Linux命令行工具

2020-05-09 12:01:40

Linux开源软件SDN

2024-01-03 10:17:51

Linux通信

2010-01-27 09:58:59

Linuxunix程序日志

2021-03-09 11:25:04

Linux开源工具服务器

2019-08-01 09:52:46

LinuxNetData性能监控工具

2012-05-22 00:28:21

JavaJava开源开源工具

2021-09-07 07:53:42

Semaphore 信号量源码

2021-08-31 09:41:57

LinuxiPhone开源工具

2021-09-01 09:47:25

Linux 工具 开发

2022-06-06 14:20:25

个人财务开源预算

2019-05-23 14:36:24

LinuxSOSReportxsos

2017-01-12 15:58:17

Linux死锁分析方法
点赞
收藏

51CTO技术栈公众号