Obtaining Exit Information of Native Child Processes

When to Use

Starting from API version 20, parent processes can register a callback function to monitor child processes and obtain their abnormal exit information, facilitating further optimizations by the parent process. The child processes to be monitored must be created by calling OH_Ability_StartNativeChildProcess or startNativeChildProcess.

Available APIs

Name Description
Ability_NativeChildProcess_ErrCode OH_Ability_RegisterNativeChildProcessExitCallback (OH_Ability_OnNativeChildProcessExit onProcessExit) Registers a callback function for detecting abnormal exit of a native child process.
Ability_NativeChildProcess_ErrCode OH_Ability_UnregisterNativeChildProcessExitCallback (OH_Ability_OnNativeChildProcessExit onProcessExit) Unregisters the callback function used for detecting abnormal exit of a native child process.

How to Develop

Linking Dynamic Libraries

libchild_process.so

Including Header Files

#include <AbilityKit/native_child_process.h>
  1. (Main process) Register and unregister the callback for abnormal exit of native child processes.

    Call OH_Ability_RegisterNativeChildProcessExitCallback to register a callback for detecting child process exits. If the return value is NCP_NO_ERROR, the registration is successful.

    Call OH_Ability_UnregisterNativeChildProcessExitCallback to unregister the callback used for detecting child process exits. If the return value is NCP_NO_ERROR, the unregistration is successful.

    #include <AbilityKit/native_child_process.h>
    #include <hilog/log.h>
    
    // ···
    
    void OnNativeChildProcessExit(int32_t pid, int32_t signal)
    {
        OH_LOG_INFO(LOG_APP, "pid: %{public}d, signal: %{public}d", pid, signal);
    }
    
    void RegisterNativeChildProcessExitCallback()
    {
        Ability_NativeChildProcess_ErrCode ret =
            OH_Ability_RegisterNativeChildProcessExitCallback(OnNativeChildProcessExit);
        if (ret != NCP_NO_ERROR) {
            OH_LOG_ERROR(LOG_APP, "register failed.");
        }
        // ···
    }
    
    void UnregisterNativeChildProcessExitCallback()
    {
        Ability_NativeChildProcess_ErrCode ret =
            OH_Ability_UnregisterNativeChildProcessExitCallback(OnNativeChildProcessExit);
        if (ret != NCP_NO_ERROR) {
            OH_LOG_ERROR(LOG_APP, "unregister failed.");
        }
        // ···
    }
    
  2. (Main process) Add build dependencies.

    Modify the CMaklist.txt file to add the dependencies. The following assumes that the main process is implemented in the library file named libmainprocesssample.so. (The implementation of the main process and child processes can be compiled to the same dynamic link library file.)

    target_link_libraries(mainprocesssample PUBLIC
        # Add the dependency of the dynamic link library of Ability Kit.
        libchild_process.so
        
        # Dependencies of other dynamic link libraries
        # ...
    )