DEV Community

SameX
SameX

Posted on

HarmonyOS IPC Kit Remote State Subscription: Resource Management Mechanism upon Process Termination

This article aims to deeply explore the technical details of the Huawei HarmonyOS Next system (up to API 12 as of now), and is summarized based on actual development practices. It mainly serves as a carrier for technical sharing and communication. Mistakes and omissions are inevitable. Colleagues are welcome to put forward valuable opinions and questions so that we can make progress together. This article is original content, and any form of reprint must indicate the source and the original author.
In HarmonyOS application development, inter - process communication (IPC) not only needs to focus on data transfer and method invocation but also requires effective management of process resources. Today, we will deeply explore the remote state subscription and resource management mechanism in the IPC Kit, especially how to ensure the reasonable recovery of resources and the stability of communication when a process terminates. This is like in a complex traffic network, when a certain section of the road (process) has a problem, how to timely notify the relevant vehicles (processes) and conduct effective traffic guidance (resource management).

Requirements for Process Resource Management and Termination Notification

Explain the resource termination mechanism to ensure the stability and resource recovery of cross - process communication

In a multi - process application environment, the life cycle of a process is dynamically changing. When a process completes its task or terminates unexpectedly due to some reason, if the related resources cannot be recovered in time, it will cause problems such as memory leaks and affect the performance and stability of the entire system. For example, in a large - scale distributed system, a service process (Server) on a device may stop running due to device failure or resource exhaustion. If the client process (Client) communicating with it does not receive timely notification and continues to send requests to this stopped service process, it will not only lead to communication failure but also may cause the client process to enter a waiting state and waste system resources.
The resource termination mechanism of the IPC Kit is designed to solve this problem. It provides a mechanism that when a remote process (Server) terminates, it can timely notify the relevant local process (Client), so that the local process can take corresponding measures, such as releasing the resources related to the remote process, updating the communication status, etc., to ensure the stability and reliability of the entire cross - process communication system. This is like in a team project, if a member (process) suddenly leaves (terminates), the team leader (other relevant processes) can immediately know and rearrange the work (manage resources) to avoid project stagnation.

Implementation of the Remote Subscription Mechanism

Use the DeathRecipient interface to register and manage remote object termination notifications

The IPC Kit provides the DeathRecipient interface, allowing developers to easily register remote object termination notifications. The following is a simple sample code (in C language as an example):

#include <IPCKit/ipc_kit.h>
// Define the type of DeathRecipient callback function
typedef void (*OH_OnDeathRecipientCallback)(void *userData);
// Custom DeathRecipient structure
typedef struct {
    OH_OnDeathRecipientCallback onDeathCallback;
    void *userData;
} MyDeathRecipient;
// DeathRecipient callback function implementation
void OnRemoteObjectDied(void *userData) {
    MyDeathRecipient *recipient = (MyDeathRecipient *)userData;
    if (recipient->onDeathCallback!= NULL) {
        recipient->onDeathCallback(recipient->userData);
    }
    // Release resources
    free(recipient);
}
// Register remote object termination notification
void RegisterDeathRecipient(OHIPCRemoteProxy *proxy, OH_OnDeathRecipientCallback callback, void *userData) {
    MyDeathRecipient *recipient = (MyDeathRecipient *)malloc(sizeof(MyDeathRecipient));
    recipient->onDeathCallback = callback;
    recipient->userData = userData;
    OHIPCRemoteProxy_AddDeathRecipient(proxy, (OHIPCDeathRecipient *)recipient);
}
Enter fullscreen mode Exit fullscreen mode

In the above code, we define a MyDeathRecipient structure to encapsulate the callback function and user data of DeathRecipient. Through the RegisterDeathRecipient function, we can register the custom DeathRecipient to the specified OHIPCRemoteProxy object. When the remote object terminates, the OnRemoteObjectDied callback function will be called, and developers can perform resource cleanup and other operations in this callback function.

Resource Management and Memory Cleanup

Use of registerDeathRecipient and unregisterDeathRecipient to ensure correct resource release

After registering the remote object termination notification, when this notification is no longer needed, we need to unregister it in time to avoid unnecessary resource occupation. The IPC Kit provides the unregisterDeathRecipient interface to achieve this function.
The following is a simple sample code showing how to register and unregister the remote object termination notification (continuing to use the above code structure):

int main() {
    // Assume that the OHIPCRemoteProxy object has been obtained here, named proxy
    OHIPCRemoteProxy *proxy = GetRemoteProxy();
    // Register remote object termination notification
    RegisterDeathRecipient(proxy, MyCallbackFunction, myUserData);
    // When the notification is no longer needed, unregister the remote object termination notification
    unregisterDeathRecipient(proxy, (OHIPCDeathRecipient *)recipient);
    // Release the resources of the proxy object
    OHIPCRemoteProxy_Destroy(proxy);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

In this example, we first register the remote object termination notification. When it is no longer needed, we unregister the notification through unregisterDeathRecipient. At the same time, we also need to pay attention to releasing the relevant resources such as the proxy object at the appropriate time to ensure the integrity of the entire resource management process.

Code Example: Code Implementation and Callback Handling of the Remote State Subscription Mechanism

The following is a more complete code example showing the entire process of the remote state subscription mechanism, including registering the notification, handling the callback, and unregistering the notification (in C language as an example):

#include <IPCKit/ipc_kit.h>
#include <stdio.h>
#include <stdlib.h>
// Define the interface descriptor
static const char *INTERFACE_DESCRIPTOR = "MY_SERVICE_INTERFACE";
// DeathRecipient callback function implementation
void OnRemoteObjectDied(void *userData) {
    printf("Remote object has died. Cleaning up resources...\n");
    // Perform resource cleanup operations here, such as releasing memory related to the remote object, closing files, etc.
    // Assume there is a resource pointer related to the remote object, resource, that needs to be released
    // free(resource);
}
int main() {
    // Get the service proxy
    OHIPCRemoteProxy *proxy = GetServiceProxy(INTERFACE_DESCRIPTOR);
    if (proxy == NULL) {
        printf("Failed to get remote proxy.\n");
        return -1;
    }
    // Register remote object termination notification
    OHIPCDeathRecipient *recipient = OH_IPCDeathRecipient_Create(OnRemoteObjectDied, NULL, NULL);
    if (recipient == NULL) {
        printf("Failed to create death recipient.\n");
        OHIPCRemoteProxy_Destroy(proxy);
        return -1;
    }
    int result = OH_IPCRemoteProxy_AddDeathRecipient(proxy, recipient);
    if (result!= OH_IPC_SUCCESS) {
        printf("Failed to register death recipient.\n");
        OH_IPCDeathRecipient_Destroy(recipient);
        OHIPCRemoteProxy_Destroy(proxy);
        return -1;
    }
    // Simulate business logic, which can be operations such as communicating with the remote object here
    //...
    // When the notification is no longer needed, unregister the remote object termination notification
    result = OH_IPCRemoteProxy_RemoveDeathRecipient(proxy, recipient);
    if (result!= OH_IPC_SUCCESS) {
        printf("Failed to unregister death recipient.\n");
    }
    OH_IPCDeathRecipient_Destroy(recipient);
    // Release the resources of the proxy object
    OHIPCRemoteProxy_Destroy(proxy);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

In this example, we first obtain the service proxy object and then register the remote object termination notification. After successful registration, some simulated business logic operations are performed (this can be replaced with real IPC communication operations according to actual needs). When the business logic is executed and there is no longer a need to pay attention to the status of the remote object, we unregister the remote object termination notification and release the relevant resources.
Through the above introduction and code examples of the IPC Kit remote state subscription and resource management mechanism, we can see that the IPC Kit provides powerful and flexible functions in process resource management. In actual development, reasonable use of these mechanisms can effectively improve the stability and performance of the application and avoid problems caused by improper process resource management. I hope that when developing HarmonyOS applications, everyone can make full use of these features to create more excellent application programs. Just like a careful housekeeper, always paying attention to every corner (process) of the house to ensure that everything is in order (proper resource management). Haha, let's explore other interesting technical knowledge together next time! 😎

Top comments (0)