CPU affinity guarantee method, computer equipment, medium and product
By obtaining CPU affinity mask parameters and Hook operations of dynamic link libraries, the problem of uncontrolled application resource usage in multi-core CPU environments is solved, and the application is able to run stably within a specified CPU core range, improving resource allocation efficiency and system stability.
Patent Information
- Application Number
- CN202511543444.4
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-10-28
- Publication Date
- 2025-11-28
- Estimated Expiration
- Not applicable · inactive patent
AI Technical Summary
In a multi-core CPU environment, existing technologies struggle to achieve continuous and stable CPU resource control, leading to unrestricted application resource usage and impacting overall system performance and resource allocation efficiency.
By obtaining the CPU affinity mask parameter, an application launcher process is created, and the CPU affinity is set using the SetProcessAffinityMask function. Combined with the Hook operation of dynamic link libraries and the Microsoft Detours library, the application's CPU affinity-related system API calls are intercepted and redirected to ensure that the application always runs within the specified CPU core range.
It enables stable operation of applications within a specified CPU core range, avoids excessive resource consumption, improves resource allocation efficiency and stability in multi-core CPU environments, and meets the needs for precise CPU resource control in specific scenarios.
Smart Images

Figure CN121029423A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of operating system technology, and in particular to a CPU affinity guarantee method, computer device, medium and product. Background Technology
[0002] With the rapid development of computer systems, multi-core CPUs have become the mainstream configuration. In a multi-core CPU environment, rationally allocating and limiting the CPU resources used by applications is of great significance for improving overall system performance and meeting the computing needs of specific scenarios.
[0003] Currently, the main ways to control application CPU resource usage include: manually setting processor affinity through Windows Task Manager; allowing child processes to inherit the CPU affinity settings of their parent processes through process inheritance; using Windows' JobObject mechanism to manage process groups in a unified manner; and dynamically adjusting CPU affinity settings during application runtime.
[0004] However, in practical applications, the above methods are difficult to achieve continuous and stable CPU resource control. Because parallel computing programs automatically adjust resource usage according to computing needs, the initially set CPU limits are often automatically exceeded, resulting in excessive consumption of system resources. Summary of the Invention
[0005] This application provides a CPU affinity guarantee method, computer device, medium, and product for ensuring that applications always run stably in a specified CPU core.
[0006] Firstly, this application provides a CPU affinity guarantee method applied to a computer device. The method includes: obtaining CPU affinity mask parameters, which are used to limit the range of CPU cores that an application is allowed to use; creating an application launcher process and setting the CPU affinity of the application launcher process to the CPU affinity mask parameters by calling the SetProcessAffinityMask function provided by the Windows operating system; creating an application process based on a preset application path using the application launcher process and injecting a pre-compiled dynamic link library into the process space of the application process, wherein the application process obtains the same CPU affinity settings as the application launcher process through the process inheritance mechanism of the Windows operating system; and calling Microsoft... The Detours library hooks preset CPU affinity-related system APIs, which include multiple system API functions. It monitors system calls initiated by application processes in real time using dynamic link libraries. When an application process calls a target system API function from the preset CPU affinity-related system APIs, the call request is redirected to a preset handler function. This handler function returns a success status code to the application process and maintains the application process's CPU affinity settings, ensuring that the application process always runs within the CPU core range defined by the CPU affinity mask parameter.
[0007] By adopting the above technical solutions, a complete and reliable CPU resource control system is constructed from multiple dimensions, effectively solving the technical problem that CPU affinity settings are easily bypassed in related technologies. First, the computer device obtains CPU affinity mask parameters to precisely limit the range of CPU cores that applications can use. Second, the computer device creates an application launcher process and sets its CPU affinity using the `SetProcessAffinityMask` function. Then, it utilizes the process inheritance mechanism of the Windows operating system to allow the application process to inherit this CPU affinity setting, ensuring that the application runs within the preset CPU core range from the outset, avoiding chaos in initial resource allocation. The computer device intercepts the preset CPU affinity-related system APIs through dynamic link library injection and hooking operations with the Microsoft Detours library. When an application attempts to call the preset CPU affinity-related system APIs to modify CPU affinity, the computer device redirects the call request to a preset processing function. This preset processing function only returns a success status code without changing the original CPU affinity setting, fundamentally preventing applications from independently bypassing CPU core restrictions. This dual guarantee mechanism of initial limitation and real-time interception not only ensures that applications always run stably within the specified CPU core range, guaranteeing the consistency of their own running performance, but also prevents individual applications from excessively consuming CPU resources, reserving sufficient resources for other applications. This significantly improves the efficiency and stability of the overall system resource allocation in a multi-core CPU environment, meeting the needs for precise and continuous control of CPU resources in specific scenarios.
[0008] In conjunction with some embodiments of the first aspect, in some embodiments, injecting a pre-compiled dynamic link library into the process space of an application process specifically includes: allocating memory space in the process space of the application process, the memory space being used to store the path string of the dynamic link library; writing the path string of the dynamic link library into the memory space using the WriteProcessMemory function provided by the Windows operating system; obtaining the memory address of the LoadLibraryA function in the kernel32.dll module of the Windows operating system; creating a remote thread in the application process, using the memory address of the LoadLibraryA function as the entry point of the remote thread, and using the address of the memory space as the parameter of the remote thread; and initializing the dynamic link library using the DllMain function to complete the injection operation.
[0009] By adopting the above technical solution, the stable and efficient injection of dynamic link libraries into the process space of the application process is ensured for subsequent hooking operations. First, the computer allocates memory space within the application process's process space, guaranteeing the independent storage of the dynamic link library's path string. Next, the computer uses the WriteProcessMemory function to write the path string into the memory space, achieving reliable transmission of external data to the application process's process space. The computer obtains the memory address of the LoadLibraryA function in the kernel32.dll module of the Windows operating system and creates a remote thread with this memory address as the entry point and the memory space address as the parameter. The execution of the remote thread triggers the LoadLibraryA function to load the dynamic link library, and finally, the DllMain function completes the initialization of the dynamic link library. The entire process strictly follows the Windows operating system's process memory management mechanism, effectively avoiding injection failures and process crashes caused by non-standard injection procedures. Compared to traditional injection methods, this improves the success rate and stability of dynamic link library injection, which is a prerequisite for subsequent real-time CPU affinity assurance through hooking operations and directly determines the feasibility and reliability of the entire CPU affinity control scheme.
[0010] In conjunction with some embodiments of the first aspect, in some embodiments, after creating a remote thread in the application process, using the memory address of the LoadLibraryA function as the entry point of the remote thread, and using the address of the memory space as a parameter of the remote thread, the method further includes: when the remote thread finishes execution, calling the GetExitCodeThread function to obtain the exit code of the remote thread; determining whether the exit code is an invalid handle or an error code to determine whether the dynamic link library injection has failed; if it is determined that the dynamic link library injection has failed, calling the TerminateProcess function to forcibly terminate the execution of the application process, and calling the VirtualFreeEx function to release the memory space.
[0011] By adopting the above technical solution, the fault tolerance and resource management capabilities of the entire CPU affinity guarantee method are further improved, effectively reducing system risks and resource waste caused by dynamic link library injection failures. After the remote thread finishes execution, the computer device obtains the exit code of the remote thread by calling the GetExitCodeThread function, thereby enabling timely and accurate determination of whether the dynamic link library injection was successful. This avoids the problem of subsequent Hook operations failing and CPU affinity control malfunctioning due to the inability to perceive the injection status. If the computer device detects an invalid handle or error code, and determines that the dynamic link library injection has failed, it immediately calls the TerminateProcess function to forcibly terminate the application process, preventing the application from arbitrarily occupying CPU resources without CPU affinity control, thus avoiding interference with overall system performance. Simultaneously, the computer device calls the VirtualFreeEx function to release previously allocated memory space, promptly reclaiming unused memory resources, preventing memory leaks, and ensuring the reasonable allocation and efficient utilization of system memory resources.
[0012] In conjunction with some embodiments of the first aspect, in some embodiments, the MicrosoftDetours library is called via a dynamic link library to perform hook operations on preset CPU affinity-related system APIs. Specifically, this includes: initializing the MicrosoftDetours library in the DllMain function of the dynamic link library; creating an array of function pointers for the preset CPU affinity-related system APIs, the array of function pointers including the original function addresses of the preset CPU affinity-related system APIs; calling the DetourTransactionBegin function of the MicrosoftDetours library to start a hook transaction; traversing the array of function pointers and redirecting the preset CPU affinity-related system APIs to their corresponding preset processing functions using the DetourAttach function; and calling the DetourTransactionCommit function to commit the hook transaction, making the hook operation effective.
[0013] By adopting the above technical solution, a standardized and executable Hook implementation process was constructed, providing key technical guarantees for accurately intercepting application calls to preset CPU affinity-related system APIs and achieving continuous control of CPU affinity. First, the computer device initializes the Microsoft Detours library in the DllMain function of the dynamic link library, ensuring that the library resources required for the Hook operation are ready and avoiding Hook failure due to incomplete library initialization. Then, the computer device creates an array of function pointers for the preset CPU affinity-related system APIs and calls the DetourTransactionBegin function to start the Hook transaction, incorporating the Hook operations of the preset CPU affinity-related system APIs into unified transaction management, ensuring the atomicity of the Hook process—all system API Hook operations either all succeed or none fail, avoiding the chaotic situation of some system APIs failing to be intercepted. The computer device traverses the function pointer array and redirects the preset CPU affinity-related system APIs to their corresponding preset processing functions through the DetourAttach function, achieving precise modification of the API call path. Finally, the computer device calls the DetourTransactionCommit function to commit the Hook transaction, ensuring that the Hook operation officially takes effect. The entire process strictly follows the usage specifications of the Microsoft Detours library, effectively solving the problems of fragmented operations, easy errors, and incomplete interception in the traditional Hook method. It ensures that all preset CPU affinity-related system APIs can be reliably intercepted, providing solid support for redirecting API calls to preset processing functions and maintaining CPU affinity unchanged, and directly guaranteeing the continuity and effectiveness of CPU affinity control.
[0014] In conjunction with some embodiments of the first aspect, in some embodiments, the method further includes: obtaining the current CPU affinity mask of the application process, comparing the current CPU affinity mask with the CPU affinity mask parameter; when the current CPU affinity mask is inconsistent with the CPU affinity mask parameter, re-calling the SetProcessAffinityMask function to restore the CPU affinity setting of the application process to the CPU affinity mask parameter.
[0015] By adopting the above technical solution, a dual guarantee of proactive monitoring and timely correction of the CPU affinity mask is constructed, further enhancing the stability of CPU affinity control and effectively addressing potential CPU affinity setting anomalies. The computer device periodically obtains the current CPU affinity mask of the application process and compares it with the CPU affinity mask parameters. This allows for real-time detection of deviations in CPU affinity settings caused by unexpected situations (such as interference from low-level system operations or third-party program influence). Compared to the passive defense method that relies solely on hooking to intercept API calls, this proactive monitoring mode can cover abnormal scenarios that may be missed by hooking operations, preventing the problem of CPU affinity settings being breached without being detected for a long time. When an inconsistency is detected between the current CPU affinity mask and the CPU affinity mask parameters, the computer device immediately calls the SetProcessAffinityMask function again to restore the CPU affinity settings to the CPU affinity mask parameters, achieving rapid correction of abnormal deviations and ensuring that the application process always returns to the preset CPU core range for operation. This method overcomes the limitations of single-hook interception, forming a complete closed loop of intercepting illegal modifications, monitoring abnormal deviations, and restoring correct settings. It significantly improves the reliability of CPU affinity protection and can effectively resist interference from various factors on CPU affinity settings even in complex system environments, ensuring the stability of application and overall system performance.
[0016] In conjunction with some embodiments of the first aspect, in some embodiments, CPU affinity mask parameters are obtained. These parameters are used to limit the range of CPU cores that an application is allowed to use. Specifically, this includes: obtaining the utilization rate of all CPU cores; sorting all CPU cores from low to high utilization rate to obtain a list of the most idle cores; determining the required number of CPU cores based on the application type and performance requirements; selecting a corresponding number of CPU core numbers from the list of the most idle cores based on the number of CPU cores; converting the CPU core numbers into binary representation; performing bitwise operations on the binary bits to generate the CPU affinity mask parameters.
[0017] By adopting the above technical solution, a dynamic CPU affinity mask parameter generation mechanism was constructed, solving the problems of unreasonable resource allocation and mismatch with application requirements in traditional fixed mask settings, and realizing precise and personalized allocation of CPU resources. First, the computer device obtains the utilization rate of all CPU cores and sorts them from low to high to generate a leaderboard of the most idle cores. This provides data support for the subsequent selection of CPU core ranges, ensuring that idle CPU cores are prioritized, avoiding competition between applications and other processes for busy core resources, thereby improving the application's own operating efficiency. Next, the computer device determines the required number of CPU cores based on the application type (e.g., compute-intensive, I / O-intensive) and performance requirements (e.g., response speed, computational accuracy), breaking the "one-size-fits-all" core allocation model and ensuring a high degree of match between the number of CPU cores and the actual application needs—for example, allocating more cores to compute-intensive applications to meet computing power requirements, and allocating fewer cores to lightweight applications to avoid resource waste. Finally, the computer device selects the corresponding number of CPU core numbers from the leaderboard of the most idle cores based on the number of CPU cores and generates CPU affinity mask parameters, realizing a resource scheduling logic of on-demand allocation and priority for idle cores. This approach allows the CPU affinity mask parameters to be flexibly adjusted according to system resource status and application characteristics, ensuring that applications obtain sufficient and suitable CPU resources while avoiding resource idleness or excessive occupation, significantly improving resource utilization efficiency in multi-core CPU environments, and providing a better hardware foundation for the stable operation of applications.
[0018] In conjunction with some embodiments of the first aspect, in some embodiments, the CPU core number is converted into a binary representation, and bitwise operations are performed on the binary bits to generate CPU affinity mask parameters. Specifically, this includes: generating a corresponding individual core mask based on each CPU core number, wherein the individual core mask is a binary value, the binary value is 1 on the bits equal to the CPU core number, and the remaining bits are 0; performing bitwise operations on all individual core masks to obtain intermediate affinity mask parameters; and converting the intermediate affinity mask parameters into decimal values to obtain CPU affinity mask parameters.
[0019] By adopting the above technical solution, firstly, the computer device generates an individual core mask based on each CPU core number; then, the computer device performs bitwise operations on all individual core masks to obtain intermediate affinity mask parameters, which are then converted into decimal values as the final CPU affinity mask parameters. Compared to the potential calculation errors and core omissions in traditional mask generation, this standardized conversion logic, through a clear process of individual identifier → merging operation → base conversion, achieves error-free conversion from CPU core number to CPU affinity mask parameters, ensuring that the generated CPU affinity mask parameters accurately correspond to the selected CPU core range. Whether for a single core or a combination of multiple cores, it can stably generate correct CPU affinity mask parameters, providing accurate parameter basis for subsequent CPU affinity settings for application launcher processes and application processes. This directly guarantees the accuracy of CPU core range limitation and is a crucial link in ensuring the accurate implementation of the entire CPU affinity guarantee method.
[0020] In a second aspect, embodiments of this application provide a computer device comprising: one or more processors and a memory; the memory is coupled to the one or more processors and is used to store computer program code, the computer program code including computer instructions, wherein the one or more processors invoke the computer instructions to cause the computer device to perform the method described in the first aspect and any possible implementation thereof.
[0021] Thirdly, embodiments of this application provide a computer program product containing instructions that, when the computer program product is run on a computer device, cause the computer device to perform the method described in the first aspect and any possible implementation thereof.
[0022] Fourthly, embodiments of this application provide a computer-readable storage medium including instructions that, when executed on a computer device, cause the computer device to perform the method described in the first aspect and any possible implementation thereof.
[0023] It is understood that the computer device provided in the second aspect, the computer program product provided in the third aspect, and the computer storage medium provided in the fourth aspect are all used to execute the methods provided in the embodiments of this application. Therefore, the beneficial effects they can achieve can be referred to the beneficial effects in the corresponding methods, and will not be repeated here.
[0024] One or more technical solutions provided in the embodiments of this application have at least the following technical effects or advantages: 1. By adopting the above technical solution, a complete and reliable CPU resource control system is constructed from multiple dimensions, effectively solving the technical problem that CPU affinity settings are easily bypassed in related technologies. First, the computer device obtains CPU affinity mask parameters to precisely limit the range of CPU cores that applications can use. Second, the computer device creates an application launcher process and sets its CPU affinity using the SetProcessAffinityMask function. Then, it utilizes the process inheritance mechanism of the Windows operating system to allow the application process to inherit this CPU affinity setting, ensuring that the application runs within the preset CPU core range from the outset, avoiding chaos in initial resource allocation. The computer device intercepts the preset CPU affinity-related system APIs through dynamic link library injection and hook operations with the Microsoft Detours library. When an application attempts to call the preset CPU affinity-related system APIs to modify CPU affinity, the computer device redirects the call request to a preset processing function. This preset processing function only returns a success status code without changing the original CPU affinity setting, fundamentally preventing applications from independently bypassing CPU core restrictions. This dual guarantee mechanism of initial limitation and real-time interception not only ensures that applications always run stably within the specified CPU core range, guaranteeing the consistency of their own running performance, but also prevents individual applications from excessively consuming CPU resources, reserving sufficient resources for other applications. This significantly improves the efficiency and stability of the overall system resource allocation in a multi-core CPU environment, meeting the needs for precise and continuous control of CPU resources in specific scenarios.
[0025] 2. By adopting the above technical solution, the dynamic link library (DLL) can be injected stably and efficiently into the application process's process space for subsequent Hook operations. First, the computer allocates memory space within the application process's process space, ensuring the independent storage of the DLL's path string. Next, the computer uses the WriteProcessMemory function to write the path string into the memory space, achieving reliable transmission of external data to the application process's process space. The computer obtains the memory address of the LoadLibraryA function in the Windows operating system's kernel32.dll module and creates a remote thread with this memory address as the entry point and the memory space address as the parameter. The execution of this remote thread triggers the LoadLibraryA function to load the DLL, and finally, the DllMain function completes the DLL initialization. The entire process strictly follows the Windows operating system's process memory management mechanism, effectively avoiding injection failures and process crashes caused by non-standard injection procedures. Compared to traditional injection methods, this improves the success rate and stability of DLL injection, which is a prerequisite for subsequent real-time CPU affinity assurance through Hook operations and directly determines the feasibility and reliability of the entire CPU affinity control scheme.
[0026] 3. By adopting the above technical solution, the fault tolerance and resource management capabilities of the entire CPU affinity guarantee method are further improved, effectively reducing system risks and resource waste caused by dynamic link library injection failure. After the remote thread finishes execution, the computer device obtains the exit code of the remote thread by calling the GetExitCodeThread function, thereby enabling timely and accurate determination of whether the dynamic link library injection was successful. This avoids the problem of subsequent Hook operations failing and CPU affinity control failing due to the inability to perceive the injection status. If the computer device detects that the exit code is an invalid handle or an error code, and determines that the dynamic link library injection has failed, it immediately calls the TerminateProcess function to forcibly terminate the application process, preventing the application from arbitrarily occupying CPU resources without CPU affinity control, thus avoiding interference with the overall system performance. At the same time, the computer device calls the VirtualFreeEx function to release the previously allocated memory space, which can promptly reclaim ineffective memory resources, prevent memory leaks, and ensure the reasonable allocation and efficient utilization of system memory resources. Attached Figure Description
[0027] Figure 1 This is a flowchart illustrating a CPU affinity guarantee method in an embodiment of this application; Figure 2This is another flowchart illustrating the CPU affinity guarantee method in the embodiments of this application; Figure 3 This is a schematic diagram of the physical device structure of a computer device in an embodiment of this application. Detailed Implementation
[0028] The terminology used in the following embodiments of this application is for the purpose of describing particular embodiments only and is not intended to be limiting of this application. As used in the specification of this application, the singular expressions “a,” “an,” “the,” “the,” and “this” are intended to include the plural expressions as well, unless the context clearly indicates otherwise. It should also be understood that the term “and / or” as used in this application refers to any or all possible combinations including one or more of the listed items.
[0029] Hereinafter, the terms "first" and "second" are used for descriptive purposes only and should not be construed as implying or suggesting relative importance or implicitly indicating the number of indicated technical features. Thus, a feature defined as "first" or "second" may explicitly or implicitly include one or more of that feature, and in the description of the embodiments of this application, unless otherwise stated, "multiple" means two or more.
[0030] The following describes the process of the method provided in this implementation. Please refer to [link / reference]. Figure 1 This is a flowchart illustrating a CPU affinity guarantee method in an embodiment of this application.
[0031] S101. Obtain the CPU affinity mask parameter. The CPU affinity mask parameter is used to limit the range of CPU cores that the application is allowed to use. The CPU affinity mask parameter is a decimal value that specifies which CPU cores an application can run on. The application refers to the target program that requires CPU affinity control. The CPU core range refers to the set of processor cores that the application is allowed to run on.
[0032] Specifically, computer devices can obtain CPU affinity mask parameters from application configuration files. These files contain different CPU affinity mask parameters for different applications; for example, "AppName=0x0F" indicates that CPUs 0-3 are allowed. The computer device reads the configuration file and retrieves the corresponding CPU affinity mask parameter based on the application's name.
[0033] Optionally, under normal circumstances, obtaining the CPU affinity mask parameter, which is used to limit the range of CPU cores that an application is allowed to use, can be achieved in the following ways, which are not limited here: obtain the utilization rate of all CPU cores, sort all CPU cores from low to high utilization rate to obtain the list of most idle cores; determine the required number of CPU cores based on the type and performance requirements of the application; select the corresponding number of CPU core numbers from the list of most idle cores based on the number of CPU cores; convert the CPU core numbers into binary representation, perform bitwise operations on the binary bits, and generate the CPU affinity mask parameter.
[0034] Specifically, CPU core utilization represents the percentage of CPU core workload. The list of least active cores is a sequence of CPU cores ranked from lowest to highest utilization. The number of CPU cores refers to the number of CPU cores allocated based on the actual needs of the application. The CPU core number is a unique identifier for each CPU core in the system.
[0035] Specifically, first, the computer device obtains the utilization data of each CPU core through Windows system APIs (such as GetSystemTimes), including kernel time, user time, and idle time, and calculates the actual utilization percentage of each CPU core. Then, the computer device sorts all CPU cores from lowest to highest utilization, generating a leaderboard of the most idle cores, prioritizing CPU cores with lower utilization to achieve load balancing. Next, the computer device determines the number of CPU cores to allocate based on the application type (e.g., compute-intensive, I / O-intensive) and performance requirements (e.g., real-time requirements, computational load). Based on the determined number of CPU cores, the corresponding number of CPU core numbers are selected from the top of the leaderboard of the most idle cores. Finally, the computer device converts the selected CPU core numbers into binary representations and combines them into a mask value, i.e., the CPU affinity mask parameter, through a bitwise OR operation. For example, when selecting CPU1 and CPU3, the generated CPU affinity mask parameter is 1010 (decimal value 10). This dynamic allocation method based on real-time resource status can better adapt to changes in system load and improve resource utilization efficiency.
[0036] Example of the most idle core leaderboard: CPU core 2 (5%) -> CPU core 0 (10%) -> CPU core 1 (15%) -> CPU core 3 (80%) -> CPU core 4 (85%) ... Determining the required number of CPU cores based on the application type and performance requirements: Light tasks (such as WPS documents, Chrome browser): do not require high computing power and can run smoothly with just 1 CPU core; Medium-intensity tasks (such as Photoshop photo editing, running multiple instances of a game): require strong responsiveness, and allocating 2 CPU cores can provide a better experience; Heavy-duty tasks (such as ANSYS Fluent simulation, video rendering, scientific computing): These are parallel computing-intensive applications. The more CPU cores allocated, the faster the computing speed. Allocate 4, 8 or more CPU cores.
[0037] Optionally, in general, converting the CPU core number into a binary representation and performing bitwise operations on the binary bits to generate the CPU affinity mask parameters can be achieved in the following ways, without limitation: Based on each CPU core number, generate a corresponding individual core mask. The individual core mask is a binary value, with 1 for the bits equal to the CPU core number and 0 for the remaining bits; perform bitwise operations on all individual core masks to obtain intermediate affinity mask parameters, and convert the intermediate affinity mask parameters into decimal values to obtain the CPU affinity mask parameters.
[0038] In this context, the individual core mask represents the binary access level identifier of a single CPU core, with each bit corresponding to a core location. The intermediate affinity mask parameter refers to the binary result of merging multiple individual core masks. A bit refers to each digit in a binary number, numbered 0, 1, 2, ... from right to left. Bitwise operations refer to bit-level operations performed on binary numbers, such as bitwise OR (|) operations.
[0039] Specifically, the computer device iterates through each selected CPU core number and generates a corresponding individual core mask for each CPU core number. The generation rule is: set the bit corresponding to the CPU core number to 1, and set the other bits to 0. For example: The individual core mask for CPU0 is: 0001 (bit 0 is 1); The individual core mask for CPU2 is: 0100 (the second bit is 1); The individual core mask for CPU3 is: 1000 (the 3rd bit is 1); Then, the computer device combines all the generated individual core masks using a bitwise OR (|) operation to obtain the intermediate affinity mask parameters. For example, if CPU0, CPU2, and CPU3 are selected, then: 0001|0100|1000=1101.
[0040] Finally, the computer device converts this intermediate binary affinity mask parameter into a decimal value (13 in this example) as the final CPU affinity mask parameter. This conversion ensures that each bit in the CPU affinity mask parameter accurately corresponds to the usage rights of a CPU core.
[0041] S102. Create an application launcher process and set the CPU affinity of the application launcher process to the CPU affinity mask parameter by calling the SetProcessAffinityMask function provided by the Windows operating system. The application launcher process refers to an intermediate process specifically designed to launch and control the target application. The `SetProcessAffinityMask` function is a system API provided by the Windows operating system, used to set the CPU affinity of a process. CPU affinity settings bind a process to a specified set of CPU cores.
[0042] Specifically, the computer device first creates a new process as the application launcher. Then, it calls the `SetProcessAffinityMask` function to set the CPU affinity mask of the launcher process to the mask parameter obtained in the previous step. At this point, the launcher process is restricted to running only on the specified CPU cores. This launcher process will act as the parent process of the target application, controlling its CPU resource usage.
[0043] S103. Based on the preset application path, an application process is created through the application launcher process, and the pre-compiled dynamic link library is injected into the process space of the application process. The application process obtains the same CPU affinity settings as the application launcher process through the process inheritance mechanism of the Windows operating system. The default application path represents the complete file system path to the application's executable file. A dynamic link library (DLL) is a DLL file containing hook code used to monitor and intercept system API calls. Process space refers to the independent virtual address space allocated by the operating system to an application process. Process inheritance is a Windows system feature where child processes automatically inherit certain attributes from their parent processes.
[0044] Specifically, first, the computer device calls the `CreateProcess` function through the application launcher process to create an application process based on a preset application path. Due to Windows' process inheritance mechanism, the newly created application process automatically inherits the CPU affinity settings of the application launcher process. Then, the computer device allocates memory space within the application process and injects pre-compiled dynamic link libraries into this memory space. After injection, the dynamic link libraries can monitor the application's system calls, preventing it from modifying the CPU affinity settings.
[0045] S104. Call the Microsoft Detours library through a dynamic link library to perform hook operations on the preset CPU affinity-related system APIs. The preset CPU affinity-related system APIs include multiple system API functions. The Microsoft Detours library refers to a library developed by Microsoft for monitoring and modifying Win32 function calls. Hooking refers to techniques that intercept or alter program behavior by modifying the function call flow. Preset CPU affinity-related system APIs refer to the set of functions provided by the Windows operating system that can modify the CPU affinity of processes, including SetProcessAffinityMask and SetThreadAffinityMask. System API functions are standard interface functions provided by the operating system for applications to call.
[0046] Specifically, first, the computer device initializes the MicrosoftDetours library in the DllMain function of the dynamic link library to ensure that the hooking function is available. Then, the computer device creates an array of function pointers to store the raw function addresses of all preset CPU affinity-related system APIs that need to be monitored. Next, the computer device calls the DetourTransactionBegin function to start a hook transaction, using the DetourAttach function to redirect each system API function in the preset CPU affinity-related system APIs to its corresponding preset processing function. For example, the SetProcessAffinityMask function is redirected to a custom MySetProcessAffinityMask function. Finally, the computer device calls the DetourTransactionCommit function to commit the hook transaction, making all hook operations take effect simultaneously. This establishes a complete API monitoring network that can intercept all system calls that may modify CPU affinity.
[0047] Optionally, under normal circumstances, hooking preset CPU affinity-related system APIs by calling the Microsoft Detours library via a dynamic link library can be achieved in the following way, without limitation: Initialize the Microsoft Detours library in the DllMain function of the dynamic link library; create an array of function pointers for the preset CPU affinity-related system APIs, including the original function addresses of the preset CPU affinity-related system APIs; call the DetourTransactionBegin function of the Microsoft Detours library to start the hook transaction; traverse the array of function pointers and redirect the preset CPU affinity-related system APIs to the corresponding preset processing functions using the DetourAttach function; call the DetourTransactionCommit function to commit the hook transaction, making the hook operation effective.
[0048] S105. Based on real-time monitoring of system calls initiated by the application process using dynamic link libraries, when it is detected that the application process calls a target system API function in the preset CPU affinity-related system API, the call request of the target system API function is redirected to a preset processing function. The preset processing function is used to return a status code of successful execution to the application process and maintain the CPU affinity setting of the application process unchanged, so as to ensure that the application process always runs within the CPU core range limited by the CPU affinity mask parameter.
[0049] In this context, a system call represents an application's action of requesting a service from the operating system. The target system API function refers to any of the pre-defined CPU affinity-related system APIs actually called by the application. The pre-defined processing function is a user-defined function used to replace the original system API. A success status code indicates a value returned to the application indicating that the operation has been successfully completed; it is typically 0 or TRUE.
[0050] Specifically, the computer continuously monitors all system calls of applications through injected dynamic link libraries. When it detects that an application is attempting to call functions such as `SetProcessAffinityMask` and `SetThreadAffinityMask` to modify its CPU affinity, the computer redirects these calls to a pre-defined handler function. This pre-defined handler function does not perform the actual CPU affinity modification; instead, it directly returns a success status code (e.g., `TRUE`). This makes the application believe that the CPU affinity modification was successful, but in reality, the original CPU affinity settings are fully preserved. For example, when an application calls `SetProcessAffinityMask(hProcess, 0xFF)` to try to gain access to all CPU cores, the pre-defined handler function intercepts this call, returns `TRUE` but does not change the actual CPU affinity settings, thus ensuring that the application always runs within the initially allocated CPU core range. This "deceptive" approach effectively maintains the limitation of CPU resource usage without affecting the normal operation of the application.
[0051] By adopting the above technical solutions, a complete and reliable CPU resource control system is constructed from multiple dimensions, effectively solving the technical problem that CPU affinity settings are easily bypassed in related technologies. First, the computer device obtains CPU affinity mask parameters to precisely limit the range of CPU cores that applications can use. Second, the computer device creates an application launcher process and sets its CPU affinity using the `SetProcessAffinityMask` function. Then, it utilizes the process inheritance mechanism of the Windows operating system to allow the application process to inherit this CPU affinity setting, ensuring that the application runs within the preset CPU core range from the outset, avoiding chaos in initial resource allocation. The computer device intercepts the preset CPU affinity-related system APIs through dynamic link library injection and hooking operations with the Microsoft Detours library. When an application attempts to call the preset CPU affinity-related system APIs to modify CPU affinity, the computer device redirects the call request to a preset processing function. This preset processing function only returns a success status code without changing the original CPU affinity setting, fundamentally preventing applications from independently bypassing CPU core restrictions. This dual guarantee mechanism of initial limitation and real-time interception not only ensures that applications always run stably within the specified CPU core range, guaranteeing the consistency of their own running performance, but also prevents individual applications from excessively consuming CPU resources, reserving sufficient resources for other applications. This significantly improves the efficiency and stability of the overall system resource allocation in a multi-core CPU environment, meeting the needs for precise and continuous control of CPU resources in specific scenarios.
[0052] The following provides a more detailed description of the process of the method provided in this implementation. Please refer to [link / reference]. Figure 2 This is another flowchart illustrating the CPU affinity guarantee method in this application embodiment.
[0053] S201. Obtain the CPU affinity mask parameter. The CPU affinity mask parameter is used to limit the range of CPU cores that the application is allowed to use.
[0054] For details, please refer to step S101, which will not be repeated here.
[0055] S202. Create an application launcher process and set the CPU affinity of the application launcher process to the CPU affinity mask parameter by calling the SetProcessAffinityMask function provided by the Windows operating system.
[0056] For details, please refer to step S102, which will not be repeated here.
[0057] S203. Based on the preset application path, an application process is created through the application launcher process. The application process obtains the same CPU affinity settings as the application launcher process through the process inheritance mechanism of the Windows operating system.
[0058] For details, please refer to step S103, which will not be repeated here.
[0059] S204. Allocate memory space in the process space of the application process. The memory space is used to store the path string of the dynamic link library.
[0060] In this context, process space refers to the independent virtual address space allocated by the operating system for application processes, used to store the application process's code, data, and other resources. Memory space refers to a contiguous region of memory allocated within process space. The path string of a dynamic link library represents the complete access path of the dynamic link library (.dll) in the file system.
[0061] Specifically, first, the computer device requests a block of memory from the application process using the Windows API function VirtualAllocEx. The size of the requested memory space needs to be large enough to store the path string of the dynamic link library (including the null terminator \0). The access permission for the memory space is set to PAGE_READWRITE, allowing subsequent writing of data to that memory space.
[0062] S205. Use the WriteProcessMemory function provided by the Windows operating system to write the path string of the dynamic link library into the memory space.
[0063] The WriteProcessMemory function is a system API provided by the Windows operating system, used to write data to the memory space of an application process.
[0064] Specifically, the computer device calls the `WriteProcessMemory` function to write the complete path string of the dynamic link library into the memory space allocated in the previous step. The write operation is synchronous, ensuring that the data is completely written before returning. The computer device checks the return value of the `WriteProcessMemory` function to verify whether the write operation was successful. If the write operation fails, the dynamic link library injection process will be terminated and the allocated memory resources will be released.
[0065] S206. Obtain the memory address of the LoadLibraryA function in the kernel32.dll module of the Windows operating system.
[0066] The kernel32.dll file is the core system file of the Windows operating system, containing essential functions required for application operation, such as file operations, memory management, process and thread control, and other critical functionalities. The LoadLibraryA function, provided by the kernel32.dll module, is an important system function that loads a specified dynamic link library into the application process's memory space and initializes it. The memory address refers to the precise location of the LoadLibraryA function in computer memory; its functionality can be invoked through this memory address.
[0067] Specifically, the computer device needs to perform the following operations: First, use the GetModuleHandle(“kernel32.dll”) function to obtain the location information of the kernel32.dll module; then use the GetProcAddress function to find the specific location of the LoadLibraryA function within the kernel32.dll module. Due to the special design of the Windows operating system, the kernel32.dll module is loaded in the same location in all programs, which means that the location of the LoadLibraryA function found in the current program is exactly the same in the target program. The computer device will save the specific location of the LoadLibraryA function within the kernel32.dll module (the memory address of the LoadLibraryA function). If, due to system abnormalities or other reasons, the memory address of the LoadLibraryA function cannot be obtained, the entire dynamic link library injection operation cannot continue and must be terminated.
[0068] S207. Create a remote thread in the application process, using the memory address of the LoadLibraryA function as the entry point of the remote thread and the address of the memory space as the parameter of the remote thread.
[0069] In this context, a remote thread refers to a new execution thread created within the application process. The entry point represents the address of the starting function from which the remote thread begins execution. Parameters are the data passed to the remote thread's entry function. The memory address of the `LoadLibraryA` function indicates where the remote thread should begin executing its code. The memory address represents the starting location of the memory region storing the path string of the dynamic link library.
[0070] Specifically, the computer device creates a remote thread within the application process by calling the CreateRemoteThread function. After successful creation, the remote thread executes the LoadLibraryA function within the application process, using the path string of the dynamic link library as a parameter to load the dynamic link library.
[0071] S208. When the remote thread finishes execution, call the GetExitCodeThread function to obtain the exit code of the remote thread.
[0072] In this context, "remote thread execution complete" means that the LoadLibraryA function has finished loading the dynamic link library within the application process. The GetExitCodeThread function is a system API provided by the Windows operating system for obtaining the execution result of a remote thread. The exit code indicates the final status value of the remote thread execution; for the LoadLibraryA function, it returns a handle to the loaded dynamic link library module on success and NULL on failure.
[0073] Specifically, the computer device uses the WaitForSingleObject function to wait for the remote thread to complete execution, setting a reasonable timeout (e.g., 5000 milliseconds) to avoid indefinite waiting. After the remote thread finishes, the computer device calls the GetExitCodeThread function, passing in the remote thread handle and the address of a variable to receive the exit code, to obtain the return value of the LoadLibraryA function. This return value directly reflects the result of loading the dynamic link library: if the return value is a valid dynamic link library module handle (non-zero value), then the loading was successful; if the return value is NULL or the GetExitCodeThread function call failed, then the loading failed.
[0074] S209. Determine if the exit code is an invalid handle or an error code to determine if the dynamic link library injection has failed.
[0075] An invalid handle refers to a dynamic link library module handle with a value of NULL (0), indicating that the dynamic link library loading failed. Error codes refer to error status values defined by the Windows operating system, such as ERROR_MOD_NOT_FOUND (123), which indicates that the specified module could not be found. Dynamic link library injection failure indicates that the dynamic link library could not be successfully loaded into the application process.
[0076] Specifically, the computer device checks the obtained exit code and compares it with known error states. If the exit code is NULL, it indicates that the LoadLibraryA function failed to execute; if the exit code is a system-defined error code, such as ERROR_INVALID_HANDLE or ERROR_ACCESS_DENIED, it also indicates that the dynamic link library injection failed. In addition, the computer device will call the GetLastError function to obtain more detailed error information to diagnose the cause of the failure. For example, if GetLastError returns ERROR_BAD_EXE_FORMAT (193), it indicates that the dynamic link library file format is incorrect; if GetLastError returns ERROR_DLL_INIT_FAILED (1114), it indicates that the dynamic link library initialization function failed to execute. This error information can provide a basis for subsequent error handling.
[0077] S210. If it is determined that the dynamic link library injection has failed, the TerminateProcess function is called to forcibly terminate the application process and the VirtualFreeEx function is called to release the memory space.
[0078] The `TerminateProcess` function is an API function provided by the Windows operating system used to forcibly terminate an application process. Forced termination means immediately stopping the execution of all threads of the application process, without waiting for it to terminate naturally. The `VirtualFreeEx` function is a system API used to release virtual memory allocated in a remote process. Releasing memory space means returning the memory space previously allocated via `VirtualAllocEx` to the operating system.
[0079] Specifically, the computer device calls the TerminateProcess function, passing in the application process handle and exit code (usually -1 indicating abnormal termination), to forcibly terminate the application process. This prevents the application from continuing to run without necessary dynamic link library support, thus preventing unpredictable behavior. Subsequently, the computer device calls the VirtualFreeEx function to ensure that all memory resources allocated in the application process are cleaned up. Furthermore, the computer device closes previously opened process handles and thread handles, completing a full resource cleanup.
[0080] S211. Initialize the dynamic link library using the DllMain function to complete the injection operation.
[0081] The `DllMain` function is the entry point function of the dynamic link library, used to perform initialization and cleanup tasks during loading and unloading. Initialization involves setting up the environment and resources required for the dynamic link library to run. The injection operation represents the entire process of loading the dynamic link library into the application process and enabling it to start working.
[0082] Specifically, after the LoadLibraryA function maps the dynamic link library file into the process address space, the Windows operating system automatically calls the dynamic link library's DllMain function, passing in the DLL_PROCESS_ATTACH event flag. The computer device performs necessary initialization operations in the DllMain function, such as initializing global variables, creating synchronization objects, and registering message callbacks. In particular, for dynamic link libraries used for CPU affinity control, the initialization process includes: saving the original system API function addresses, initializing the Microsoft Detours library, and setting up the data structures required for hooking. The DllMain function returns TRUE to indicate successful initialization, at which point the dynamic link library injection operation is complete; the DllMain function returns FALSE to indicate initialization failure, at which point the Windows operating system automatically unloads the dynamic link library and notifies the LoadLibraryA function that the call failed. Computer devices need to pay special attention to thread safety issues when implementing the DllMain function, avoiding performing time-consuming operations or calling unsafe APIs in the DLL_PROCESS_ATTACH event handler.
[0083] S212. By calling the Microsoft Detours library through a dynamic link library, hook operations are performed on the preset CPU affinity-related system APIs, which include multiple system API functions.
[0084] For details, please refer to step S104, which will not be repeated here.
[0085] S213. Based on real-time monitoring of system calls initiated by the application process using dynamic link libraries, when it is detected that the application process calls a target system API function in the preset CPU affinity-related system API, the call request of the target system API function is redirected to a preset processing function. The preset processing function is used to return a status code of successful execution to the application process and maintain the CPU affinity setting of the application process unchanged, so as to ensure that the application process always runs within the CPU core range limited by the CPU affinity mask parameter.
[0086] For details, please refer to step S105, which will not be repeated here.
[0087] S214. Obtain the current CPU affinity mask of the application process and compare the current CPU affinity mask with the CPU affinity mask parameters.
[0088] Here, the current CPU affinity mask refers to the range of CPU cores actually used by the application process at this moment. The CPU affinity mask parameter refers to the range of CPU cores that the application is expected to restrict to be used. The comparison operation represents the process of checking whether the current CPU affinity mask and the CPU affinity mask parameter are exactly the same.
[0089] Specifically, the computer device obtains the current CPU affinity mask of the application process by calling the GetProcessAffinityMask function. After obtaining the current CPU affinity mask, the computer device compares it with the CPU affinity mask parameter. This comparison process involves checking if every bit of the current CPU affinity mask is exactly the same as the CPU affinity mask parameter; any difference in any bit indicates that the CPU affinity setting has been modified. For example, if the CPU affinity mask parameter is 0x0F (allowing the use of CPU0-CPU3), while the current CPU affinity mask is 0x1F (allowing the use of CPU0-CPU4), it means that the CPU affinity setting has been expanded.
[0090] S215. When the current CPU affinity mask is inconsistent with the CPU affinity mask parameter, the SetProcessAffinityMask function is called again to restore the CPU affinity setting of the application process to the CPU affinity mask parameter.
[0091] The `SetProcessAffinityMask` function is a system API provided by the Windows operating system for setting the CPU affinity of application processes. "Restore" refers to the operation of resetting the CPU affinity of the application process to the CPU affinity mask parameter.
[0092] Specifically, when the computer device detects an inconsistency between the current CPU affinity mask and the CPU affinity mask parameters, it immediately calls the `SetProcessAffinityMask` function to correct it. The computer device checks the return value of the `SetProcessAffinityMask` function to ensure successful correction. If the correction fails, the computer device logs the error information and retryes in the next check cycle. This continuous monitoring and timely correction mechanism ensures that applications always run within the preset CPU core range, and even if other programs or system operations attempt to modify the CPU affinity settings, they will be immediately detected and corrected. For example, if a third-party tool attempts to change an application's CPU affinity from 0x03 (CPU0-CPU1) to 0xFF (all CPU cores), the modification will be detected and restored to 0x03 in the next check, thus maintaining the expected CPU resource usage limits.
[0093] The computer device in the embodiments of this invention is described below from the perspective of hardware processing. Please refer to [link / reference needed]. Figure 3 This is a schematic diagram of the physical device structure of a computer device in an embodiment of this application.
[0094] It should be noted that, Figure 3 The structure of the computer device shown is merely an example and should not impose any limitation on the functionality and scope of use of the embodiments of the present invention.
[0095] like Figure 3 As shown, the computer device includes a CPU 301, which can perform various appropriate actions and processes according to a program stored in the read-only memory ROM 302 or a program loaded from the storage section 308 into the random access memory RAM 303, such as performing the methods described in the above embodiments. The RAM 303 also stores various programs and data required for system operation. The CPU 301, ROM 302, and RAM 303 are interconnected via a bus 304. An I / O interface 305 is also connected to the bus 304.
[0096] The following components are connected to I / O interface 305: input section 306 including audio input devices, push-button switches, etc.; output section 307 including a liquid crystal display (LCD) and audio output devices, indicator lights, etc.; storage section 308 including a hard disk, etc.; and communication section 309 including a network interface card such as a LAN (Local Area Network) card, modem, etc. Communication section 309 performs communication processing via a network such as the Internet. Drive 310 is also connected to I / O interface 305 as needed. Removable media 311, such as a disk, optical disk, magneto-optical disk, semiconductor memory, etc., are installed on drive 310 as needed so that computer programs read from them can be installed into storage section 308 as needed.
[0097] In particular, according to embodiments of the present invention, the processes described above with reference to the flowcharts can be implemented as computer software programs. For example, embodiments of the present invention include a computer program product comprising a computer program carried on a computer-readable medium, the computer program containing computer programs for performing the methods shown in the flowcharts. In such embodiments, the computer program can be downloaded and installed from a network via communication section 309, and / or installed from removable medium 311. When the computer program is executed by CPU 301, it performs the various functions defined in the present invention.
[0098] It should be noted that specific examples of computer-readable storage media may include, but are not limited to: electrical connections having one or more wires, portable computer disks, hard disks, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM), flash memory, optical fiber, portable compact disc read-only memory (CD-ROM), optical storage devices, magnetic storage devices, or any suitable combination thereof. In this invention, a computer-readable storage medium can be any tangible medium containing or storing a program that can be used by or in conjunction with an instruction execution system, apparatus, or device.
[0099] The flowcharts and block diagrams in the accompanying drawings illustrate the architecture, functionality, and operation of possible implementations of systems, methods, and computer program products according to various embodiments of the present invention. Each block in a flowchart or block diagram may represent a module, program segment, or portion of code, which contains one or more executable instructions for implementing a specified logical function. It should also be noted that in some alternative implementations, the functions indicated in the blocks may occur in a different order than those shown in the drawings.
[0100] Specifically, the computer device in this embodiment includes a processor and a memory. The memory stores a computer program. When the computer program is executed by the processor, it implements the CPU affinity guarantee method provided in the above embodiment.
[0101] In another aspect, the present invention also provides a computer-readable storage medium, which may be included in the computer device described in the above embodiments; or it may exist independently and not assembled into the computer device. The storage medium carries one or more computer programs that, when executed by a processor of the computer device, cause the computer device to implement the CPU affinity guarantee method provided in the above embodiments.
[0102] The above-described embodiments are only used to illustrate the technical solutions of this application, and are not intended to limit it. Although this application has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some of the technical features. Such modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the scope of the technical solutions of the embodiments of this application.
[0103] As used in the above embodiments, depending on the context, the term "when..." can be interpreted as meaning "if...", "after...", "in response to determining...", or "in response to detecting...". Similarly, depending on the context, the phrase "when determining..." or "if (the stated condition or event) is interpreted as meaning "if determining...", "in response to determining...", "when (the stated condition or event) is detected", or "in response to detecting (the stated condition or event)".
[0104] Those skilled in the art will understand that all or part of the processes in the methods of the above embodiments can be implemented by a computer program instructing related hardware. This program can be stored in a computer-readable storage medium, and when executed, it can include the processes described in the above method embodiments. The aforementioned storage medium includes various media capable of storing program code, such as ROM or random access memory (RAM), magnetic disks, or optical disks.
Claims
1. A method for ensuring CPU affinity, characterized in that, Applied to a computer device, the method includes: Obtain CPU affinity mask parameters, which are used to limit the range of CPU cores that the application is allowed to use; Create an application launcher process and set the CPU affinity of the application launcher process to the CPU affinity mask parameter by calling the SetProcessAffinityMask function provided by the Windows operating system; Based on the preset application path, an application process is created through the application launcher process, and a pre-compiled dynamic link library is injected into the process space of the application process. The application process obtains the same CPU affinity settings as the application launcher process through the process inheritance mechanism of the Windows operating system. The Microsoft Detours library is called through the dynamic link library to perform hook operations on preset CPU affinity-related system APIs, which include multiple system API functions. Based on the real-time monitoring of system calls initiated by the application process using the dynamic link library, when the application process is detected to call a target system API function in the preset CPU affinity-related system API, the call request of the target system API function is redirected to a preset processing function. The preset processing function is used to return a status code of successful execution to the application process and maintain the CPU affinity setting of the application process unchanged, so as to ensure that the application process always runs within the CPU core range defined by the CPU affinity mask parameter.
2. The method according to claim 1, characterized in that, The step of injecting the pre-compiled dynamic link library into the process space of the application process specifically includes: Allocate memory space in the process space of the application process, the memory space being used to store the path string of the dynamic link library; The path string of the dynamic link library is written into the memory space using the WriteProcessMemory function provided by the Windows operating system. Obtain the memory address of the LoadLibraryA function in the kernel32.dll module of the Windows operating system; A remote thread is created in the application process, with the memory address of the LoadLibraryA function as the entry point of the remote thread and the address of the memory space as the parameter of the remote thread. The dynamic link library is initialized using the DllMain function to complete the injection operation.
3. The method according to claim 2, characterized in that, After the steps of creating a remote thread in the application process, using the memory address of the LoadLibraryA function as the entry point of the remote thread, and using the address of the memory space as a parameter of the remote thread, the method further includes: When the remote thread finishes execution, the GetExitCodeThread function is called to obtain the exit code of the remote thread; Determine whether the exit code is an invalid handle or an error code to determine whether the dynamic link library injection has failed. If the dynamic link library injection fails, the TerminateProcess function is called to forcibly terminate the application process, and the VirtualFreeEx function is called to release the memory space.
4. The method according to claim 1, characterized in that, The step of calling the MicrosoftDetours library through the dynamic link library to hook preset CPU affinity-related system APIs specifically includes: The Microsoft Detours library is initialized in the DllMain function of the dynamic link library; Create an array of function pointers for the preset CPU affinity-related system APIs, wherein the array of function pointers includes the original function addresses of the preset CPU affinity-related system APIs; Call the DetourTransactionBegin function of the Microsoft Detours library to start the Hook transaction; Traverse the array of function pointers and use the DetourAttach function to redirect the preset CPU affinity-related system APIs to the corresponding preset processing functions; Call the DetourTransactionCommit function to commit the Hook transaction, making the Hook operation effective.
5. The method according to claim 1, characterized in that, The method further includes: Obtain the current CPU affinity mask of the application process, and compare the current CPU affinity mask with the CPU affinity mask parameters; When the current CPU affinity mask is inconsistent with the CPU affinity mask parameter, the SetProcessAffinityMask function is called again to restore the CPU affinity setting of the application process to the CPU affinity mask parameter.
6. The method according to claim 1, characterized in that, The step of obtaining the CPU affinity mask parameter, which is used to limit the range of CPU cores that the application is allowed to use, specifically includes: The utilization rate of each CPU core is obtained, and the CPU cores are sorted from low to high according to the utilization rate to obtain the list of the least idle cores. Determine the required number of CPU cores based on the type and performance requirements of the application; Based on the number of CPU cores, select a corresponding number of CPU core numbers from the list of most idle cores; The CPU core number is converted into a binary representation, and bitwise operations are performed on the binary bits to generate the CPU affinity mask parameters.
7. The method according to claim 6, characterized in that, The step of converting the CPU core number into a binary representation, performing bitwise operations on the binary bits, and generating the CPU affinity mask parameters specifically includes: Based on each CPU core number, a corresponding individual core mask is generated. The individual core mask is a binary value, where the binary value is 1 in the bit that is equal to the CPU core number, and the remaining bits are 0. Perform bitwise operations on all the individual core masks to obtain intermediate affinity mask parameters, and convert the intermediate affinity mask parameters into decimal values to obtain the CPU affinity mask parameters.
8. A computer device, characterized in that, The computer device includes: one or more processors and a memory; the memory is coupled to the one or more processors, the memory is used to store computer program code, the computer program code including computer instructions, and the one or more processors call the computer instructions to cause the computer device to perform the method as described in any one of claims 1-7.
9. A computer-readable storage medium comprising instructions, characterized in that, When the instructions are executed on a computer device, the computer device performs the method as described in any one of claims 1-7.
10. A computer program product, characterized in that, When the computer program product is run on a computer device, the computer device performs the method as described in any one of claims 1-7.
Citation Information
Patent Citations
Method and apparatus for improving application execution efficiency
CN108170534A
CPU scheduling method and related equipment
CN120560831A
Process management method and apparatus
WO2018099292A1
Cited By
Method for improving real-time performance of Linux operating system application program based on multi-core CPU
CN122132148A
A method for improving the real-time performance of Linux operating system applications based on multi-core CPUs
CN122132148B
