1# @ohos.app.ability.childProcessManager (childProcessManager) 2 3The **childProcessManager** module provides the child process management capability. Currently, it provides APIs to start a child process and is valid only for 2-in-1 devices and tables. 4 5The created child process does not support the UI or the calling of context-related APIs. 6 7A maximum of 512 child processes can be started through this module (non-SELF_FORK mode) and [ChildProcess](c-apis-ability-childprocess.md). 8 9> **NOTE** 10> 11> The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version. 12> 13> The APIs of this module can be used only in the stage model. 14 15## Modules to Import 16 17```ts 18import { childProcessManager } from '@kit.AbilityKit'; 19``` 20 21## StartMode 22 23Enumerates the child process start modes. 24 25**System capability**: SystemCapability.Ability.AbilityRuntime.Core 26 27| Name | Value | Description | 28| -------- | ----------------- | ----------------- | 29| SELF_FORK | 0 | The child process is forked from the application process. Binder IPC cannot be called in such a child process. Otherwise, the child process will crash. Asynchronous ArkTS API calls are not supported.| 30| APP_SPAWN_FORK | 1 | The child process is forked from AppSpawn. Such a child process does not inherit the parent process resources. It does not have application context and therefore does not support API calls that depend on application context.| 31 32## childProcessManager.startChildProcess 33 34startChildProcess(srcEntry: string, startMode: StartMode): Promise<number> 35 36Creates a child process and invokes the entrypoint method of the child process. This API uses a promise to return the result. 37 38A PID is returned once the child process is created. However, this does not mean that the child process is started. It is started only when [ChildProcess.onStart](js-apis-app-ability-childProcess.md#childprocessonstart) is successfully called. This API cannot be called by a child process to create its child process. 39 40**System capability**: SystemCapability.Ability.AbilityRuntime.Core 41 42**Parameters** 43 44| Name| Type| Mandatory| Description| 45| -------- | -------- | -------- | -------- | 46| srcEntry | string | Yes| Path of the source file of the child process relative to the root directory **src/main**. The source file can be stored only in the module of the entry type. For example, if the source file of a child process is **src/main/ets/process/DemoProcess.ets** in the entry module, then **srcEntry** is **./ets/process/DemoProcess.ets**.<br>In addition, ensure that the source file of the child process is referenced by other files to prevent it from being optimized by the build tool. (For details, see the sample code below.)| 47| startMode | [StartMode](#startmode) | Yes| Start mode of the child process.| 48 49**Return value** 50 51| Type| Description| 52| -------- | -------- | 53| Promise<number> | Promise used to return the PID of the child process.| 54 55**Error codes** 56 57 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 58 59| ID| Error Message| 60| ------- | -------- | 61| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. | 62| 16000050 | Internal error. | 63| 16000061 | Operation not supported. | 64| 16000062 | The number of child processes exceeds the upper limit. | 65 66**Example** 67 68```ts 69// Create the child process class DemoProcess.ets in src/main/ets/process of the entry module. 70// entry/src/main/ets/process/DemoProcess.ets 71import { ChildProcess } from '@kit.AbilityKit'; 72 73export default class DemoProcess extends ChildProcess { 74 onStart() { 75 console.log("DemoProcess OnStart() called"); 76 } 77} 78``` 79 80<!--code_no_check--> 81```ts 82// Call childProcessManager.startChildProcess to start the child process. 83// entry/src/main/ets/tool/Tool.ets 84import { childProcessManager } from '@kit.AbilityKit'; 85import { BusinessError } from '@kit.BasicServicesKit'; 86import DemoProcess from '../process/DemoProcess'; 87 88try { 89 DemoProcess.toString(); // Call any API of the DemoProcess class to prevent the code from being directly optimized by the compiler because it is not being referenced. 90 childProcessManager.startChildProcess("./ets/process/DemoProcess.ets", childProcessManager.StartMode.SELF_FORK) 91 .then((data) => { 92 console.log(`startChildProcess success, pid: ${data}`); 93 }, (err: BusinessError) => { 94 console.error(`startChildProcess error, errorCode: ${err.code}`); 95 }) 96} catch (err) { 97 console.error(`startChildProcess error, errorCode: ${(err as BusinessError).code}`); 98} 99``` 100 101## childProcessManager.startChildProcess 102 103startChildProcess(srcEntry: string, startMode: StartMode, callback: AsyncCallback<number>): void 104 105Creates a child process and invokes the entrypoint method of the child process. This API uses an asynchronous callback to return the result. 106 107A PID is returned once the child process is created. However, this does not mean that the child process is started. It is started only when [ChildProcess.onStart](js-apis-app-ability-childProcess.md#childprocessonstart) is successfully called. This API cannot be called by a child process to create its child process. 108 109**System capability**: SystemCapability.Ability.AbilityRuntime.Core 110 111**Parameters** 112 113| Name| Type| Mandatory| Description| 114| -------- | -------- | -------- | -------- | 115| srcEntry | string | Yes| Path of the source file of the child process relative to the root directory **src/main**. The source file can be stored only in the module of the entry type. For example, if the source file of a child process is **src/main/ets/process/DemoProcess.ets** in the entry module, then **srcEntry** is **./ets/process/DemoProcess.ets**.<br>In addition, ensure that the source file of the child process is referenced by other files to prevent it from being optimized by the build tool. (For details, see the sample code below.)| 116| startMode | [StartMode](#startmode) | Yes| Start mode of the child process.| 117| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the subprocess is started, **err** is **undefined** and **data** is the PID of the child process. Otherwise, **data** is an error object.| 118 119**Error codes** 120 121 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 122 123| ID| Error Message| 124| ------- | -------- | 125| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. | 126| 16000050 | Internal error. | 127| 16000061 | Operation not supported. | 128| 16000062 | The number of child processes exceeds the upper limit. | 129 130**Example** 131 132```ts 133// Create the child process class DemoProcess.ets in src/main/ets/process of the entry module. 134// entry/src/main/ets/process/DemoProcess.ets 135import { ChildProcess } from '@kit.AbilityKit'; 136 137export default class DemoProcess extends ChildProcess { 138 onStart() { 139 console.log("DemoProcess OnStart() called"); 140 } 141} 142``` 143 144<!--code_no_check--> 145```ts 146// Call childProcessManager.startChildProcess to start the child process. 147// entry/src/main/ets/tool/Tool.ets 148import { childProcessManager } from '@kit.AbilityKit'; 149import { BusinessError } from '@kit.BasicServicesKit'; 150import DemoProcess from '../process/DemoProcess'; 151 152try { 153 DemoProcess.toString(); // Call any API of the DemoProcess class to prevent the code from being directly optimized by the compiler because it is not being referenced. 154 childProcessManager.startChildProcess("./ets/process/DemoProcess.ets", childProcessManager.StartMode.SELF_FORK, (err, data) => { 155 if (data) { 156 console.log(`startChildProcess success, pid: ${data}`); 157 } else { 158 console.error(`startChildProcess error, errorCode: ${err.code}`); 159 } 160 }); 161} catch (err) { 162 console.error(`startChildProcess error, errorCode: ${(err as BusinessError).code}`); 163} 164``` 165 166## childProcessManager.startArkChildProcess<sup>12+</sup> 167 168startArkChildProcess(srcEntry: string, args: ChildProcessArgs, options?: ChildProcessOptions): Promise<number> 169 170Creates a child process and invokes the entrypoint method of the child process. This API uses a promise to return the result. 171 172The child process does not inherit the resources of the parent process. A PID is returned once the child process is created. However, this does not mean that the child process is started. It is started only when [ChildProcess.onStart](js-apis-app-ability-childProcess.md#childprocessonstart) is successfully called. This API cannot be called by a child process to create its child process. 173 174The child process supports parameter transfer and asynchronous ArkTS API calls (except for some APIs that depend on application context). After [ChildProcess.onStart](js-apis-app-ability-childProcess.md#childprocessonstart) is called, the child process will not be automatically destroyed. Instead, you must call [process.abort](../apis-arkts/js-apis-process.md#processabort) to destroy the child process. After the main process is destroyed, the child processes are also destroyed. 175 176**System capability**: SystemCapability.Ability.AbilityRuntime.Core 177 178**Parameters** 179 180| Name| Type| Mandatory| Description| 181| -------- | -------- | -------- | -------- | 182| srcEntry | string | Yes| Path of the source file of the child process relative to the root directory **src/main**. The source file cannot be stored in the module of the HAR type. The value consists of a module name, a slash (/), and a file path. For example, if the child process file is **src/main/ets/process/DemoProcess.ets** in module1, then **srcEntry** is **module1/./ets/process/DemoProcess.ets**.<br>In addition, ensure that the source file of the child process is referenced by other files to prevent it from being optimized by the build tool. (For details, see the sample code below.)| 183| args | [ChildProcessArgs](js-apis-app-ability-childProcessArgs.md) | Yes| Parameters transferred to the child process.| 184| options | [ChildProcessOptions](js-apis-app-ability-childProcessOptions.md) | No| Startup configuration of the child process.| 185 186**Return value** 187 188| Type| Description| 189| -------- | -------- | 190| Promise<number> | Promise used to return the PID of the child process.| 191 192**Error codes** 193 194 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 195 196| ID| Error Message| 197| ------- | -------- | 198| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. | 199| 801 | Capability not supported. | 200| 16000050 | Internal error. | 201| 16000061 | Operation not supported. The API cannot be called in a child process. | 202| 16000062 | The number of child processes exceeds the upper limit. | 203 204**Example** 205 206Sample code for the child process: 207 208```ts 209// Create the child process class DemoProcess.ets in src/main/ets/process of module1. 210// module1/src/main/ets/process/DemoProcess.ets 211import { ChildProcess, ChildProcessArgs } from '@kit.AbilityKit'; 212 213export default class DemoProcess extends ChildProcess { 214 215 onStart(args?: ChildProcessArgs) { 216 let entryParams = args?.entryParams; 217 let fd = args?.fds?.key1; 218 // .. 219 } 220} 221``` 222 223Sample code for the main process is provided below. For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 224 225<!--code_no_check--> 226```ts 227// Call childProcessManager.startArkChildProcess to start the child process. 228// module1/src/main/ets/tool/Tool.ets 229import { common, ChildProcessArgs, ChildProcessOptions, childProcessManager } from '@kit.AbilityKit'; 230import fs from '@ohos.file.fs'; 231import { BusinessError } from '@kit.BasicServicesKit'; 232import DemoProcess from '../process/DemoProcess'; 233 234try { 235 DemoProcess.toString(); // Call any API of the DemoProcess class to prevent the code from being directly optimized by the compiler because it is not being referenced. 236 let context = getContext(this) as common.UIAbilityContext; 237 let path = context.filesDir + "/test.txt"; 238 let file = fs.openSync(path, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE); 239 let args: ChildProcessArgs = { 240 entryParams: "testParam", 241 fds: { 242 "key1": file.fd 243 } 244 }; 245 let options: ChildProcessOptions = { 246 isolationMode: false 247 }; 248 childProcessManager.startArkChildProcess("module1/./ets/process/DemoProcess.ets", args, options) 249 .then((pid) => { 250 console.info(`startChildProcess success, pid: ${pid}`); 251 }) 252 .catch((err: BusinessError) => { 253 console.error(`startChildProcess business error, errorCode: ${err.code}, errorMsg:${err.message}`); 254 }) 255} catch (err) { 256 console.error(`startChildProcess error, errorCode: ${err.code}, errorMsg:${err.message}`); 257} 258``` 259 260## childProcessManager.startNativeChildProcess<sup>13+</sup> 261 262startNativeChildProcess(entryPoint: string, args: ChildProcessArgs, options?: ChildProcessOptions): Promise<number> 263 264Starts a native child process, loads the specified dynamic library file, and calls the entry function. This API uses a promise to return the result. 265 266The child process does not inherit the resources of the main process. A PID is returned once the child process is created. However, this does not mean that the entry function is successfully called, which depends on the execution result of the entry function of the child process. This API cannot be called by a child process to create its child process. It cannot be called to create a child process in an ArkTS basic runtime environment. 267 268After the entry function is executed, the child process is automatically destroyed. After the main process is destroyed, the child processes are also destroyed. 269 270**System capability**: SystemCapability.Ability.AbilityRuntime.Core 271 272**Parameters** 273 274| Name| Type| Mandatory| Description| 275| -------- | -------- | -------- | -------- | 276| entryPoint | string | Yes| The symbol and entry function of the dynamic link library called in the child process are separated by a colon (:), for example, **libentry.so:Main**.| 277| args | [ChildProcessArgs](js-apis-app-ability-childProcessArgs.md) | Yes| Parameters transferred to the child process.| 278| options | [ChildProcessOptions](js-apis-app-ability-childProcessOptions.md) | No| Startup configuration of the child process.| 279 280**Return value** 281 282| Type| Description| 283| -------- | -------- | 284| Promise<number> | Promise used to return the PID of the child process.| 285 286**Error codes** 287 288 For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 289 290| ID| Error Message| 291| ------- | -------- | 292| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. | 293| 801 | Capability not supported. Capability not supported. Failed to call the API due to limited device capabilities. | 294| 16000050 | Internal error. | 295| 16000061 | Operation not supported. The API cannot be called in a child process. | 296| 16000062 | The number of child processes exceeds the upper limit. | 297 298**Example** 299 300Sample code for the child process is provided below. For details, see [Native Child Process Development (C/C++) - Creating a Child Process That Supports Pass-by-Parameter](../../application-models/capi_nativechildprocess_development_guideline.md#creating-a-child-process-that-supports-pass-by-parameter). 301 302```c++ 303#include <AbilityKit/native_child_process.h> 304 305extern "C" { 306 307/** 308 * Entry function of a child process, which implements the service logic of the child process. 309 * The function name can be customized and is specified when the main process calls the OH_Ability_StartNativeChildProcess method. In this example, the function name is Main. 310 * After the function is returned, the child process exits. 311 */ 312void Main(NativeChildProcess_Args args) 313{ 314 // Obtain the input entryPrams. 315 char *entryParams = args.entryParams; 316 // Obtain the input FD list, corresponding to args.fds in ChildProcessArgs. 317 NativeChildProcess_Fd *current = args.fdList.head; 318 while (current != nullptr) { 319 char *fdName = current->fdName; 320 int32_t fd = current->fd; 321 current = current->next; 322 // Service logic 323 } 324} 325} // extern "C" 326``` 327 328Sample code for the main process is provided below. For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 329 330```ts 331// Main process: 332// Call childProcessManager.startNativeChildProcess to start the child process. 333import { common, ChildProcessArgs, ChildProcessOptions, childProcessManager } from '@kit.AbilityKit'; 334import fs from '@ohos.file.fs'; 335import { BusinessError } from '@kit.BasicServicesKit'; 336 337try { 338 let context = getContext(this) as common.UIAbilityContext; 339 let path = context.filesDir + "/test.txt"; 340 let file = fs.openSync(path, fs.OpenMode.READ_ONLY | fs.OpenMode.CREATE); 341 let args: ChildProcessArgs = { 342 entryParams: "testParam", 343 fds: { 344 "key1": file.fd 345 } 346 }; 347 let options: ChildProcessOptions = { 348 isolationMode: false 349 }; 350 childProcessManager.startNativeChildProcess("libentry.so:Main", args, options) 351 .then((pid) => { 352 console.info(`startChildProcess success, pid: ${pid}`); 353 }) 354 .catch((err: BusinessError) => { 355 console.error(`startChildProcess business error, errorCode: ${err.code}, errorMsg:${err.message}`); 356 }) 357} catch (err) { 358 console.error(`startChildProcess error, errorCode: ${err.code}, errorMsg:${err.message}`); 359} 360``` 361 362 <!--no_check-->