• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.app.ability.childProcessManager (Child Process Management)
2<!--Kit: Ability Kit-->
3<!--Subsystem: Ability-->
4<!--Owner: @SKY2001-->
5<!--Designer: @jsjzju-->
6<!--Tester: @lixueqing513-->
7<!--Adviser: @huipeizi-->
8
9The childProcessManager module provides the child process management capability. Currently, it provides APIs to create and start a child process
10
11> **NOTE**
12>
13> 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.
14>
15> The APIs of this module can be used only in the stage model.
16
17## Constraints
18
19- The APIs of this module work only for 2-in-1 devices and tablets.
20
21- The child processes created through the APIs of this module have the following restrictions:
22  - The created child process does not support the creation of UIs.
23  - The created child process does not support API calls that depend on the Context module (including the APIs of the Context module and the APIs that use the Context instance as an input parameter).
24  - The created child process does not support the creation of its own child process.
25
26- A maximum of 512 child processes can be started by using the APIs of this module and the APIs defined in [native_child_process.h](capi-native-child-process-h.md) (as long as system resources are sufficient). The child processes started by [startChildProcess](#childprocessmanagerstartchildprocess) in SELF_FORK mode are not counted.
27
28## Modules to Import
29
30```ts
31import { childProcessManager } from '@kit.AbilityKit';
32```
33
34## StartMode
35
36Enumerates the child process start modes.
37
38**System capability**: SystemCapability.Ability.AbilityRuntime.Core
39
40| Name                      | Value                            | Description                             |
41| --------                     |  -----------------               |  -----------------               |
42| SELF_FORK |  0   | The child process is forked from the application process. The child process started in this mode inherits the resources of the parent process and cannot use Binder IPC to communicate with other processes. Otherwise, the child process will crash.|
43| APP_SPAWN_FORK |  1   | The child process is forked from AppSpawn. The child process started in this mode does not inherit the resources of the parent process and can use Binder IPC to communicate with other processes.|
44
45## childProcessManager.startChildProcess
46
47startChildProcess(srcEntry: string, startMode: StartMode): Promise&lt;number&gt;
48
49Starts an [ArkTS child process](../../application-models/ability-terminology.md#arkts-child-process). This API uses a promise to return the result.
50
51
52> **NOTE**
53>
54> If the child process is created successfully, its PID is returned, and its [ChildProcess.onStart](js-apis-app-ability-childProcess.md#childprocessonstart) function is executed. Once the function is done, the child process is automatically destroyed.
55>
56> The child process started by calling this API does not support asynchronous ArkTS API calls. It supports only synchronous ArkTS API calls.
57
58**System capability**: SystemCapability.Ability.AbilityRuntime.Core
59
60**Parameters**
61
62  | Name| Type| Mandatory| Description|
63  | -------- | -------- | -------- | -------- |
64  | 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.)|
65  | startMode | [StartMode](#startmode) | Yes| Start mode of the child process.|
66
67**Return value**
68
69  | Type| Description|
70  | -------- | -------- |
71  | Promise&lt;number&gt; | Promise used to return the PID of the child process.|
72
73**Error codes**
74
75  For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
76
77| ID| Error Message|
78| ------- | -------- |
79| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. |
80| 16000050 | Internal error. |
81| 16000061  | Operation not supported. |
82| 16000062  | The number of child processes exceeds the upper limit. |
83
84**Example**
85
86```ts
87// Create the child process class DemoProcess.ets in src/main/ets/process of the entry module.
88// entry/src/main/ets/process/DemoProcess.ets
89import { ChildProcess } from '@kit.AbilityKit';
90
91export default class DemoProcess extends ChildProcess {
92  onStart() {
93    console.log("DemoProcess OnStart() called");
94  }
95}
96```
97
98<!--code_no_check-->
99```ts
100// Call childProcessManager.startChildProcess to start the child process.
101// entry/src/main/ets/tool/Tool.ets
102import { childProcessManager } from '@kit.AbilityKit';
103import { BusinessError } from '@kit.BasicServicesKit';
104import DemoProcess from '../process/DemoProcess';
105
106try {
107  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.
108  childProcessManager.startChildProcess("./ets/process/DemoProcess.ets", childProcessManager.StartMode.SELF_FORK)
109    .then((data) => {
110      console.log(`startChildProcess success, pid: ${data}`);
111    }, (err: BusinessError) => {
112      console.error(`startChildProcess error, errorCode: ${err.code}`);
113    })
114} catch (err) {
115  console.error(`startChildProcess error, errorCode: ${(err as BusinessError).code}`);
116}
117```
118
119## childProcessManager.startChildProcess
120
121startChildProcess(srcEntry: string, startMode: StartMode, callback: AsyncCallback&lt;number&gt;): void
122
123Starts an [ArkTS child process](../../application-models/ability-terminology.md#arkts-child-process). This API uses an asynchronous callback to return the result.
124
125> **NOTE**
126>
127> If the child process is created successfully, its PID is returned, and its [ChildProcess.onStart](js-apis-app-ability-childProcess.md#childprocessonstart) function is executed. Once the function is done, the child process is automatically destroyed.
128>
129> The child process started by calling this API does not support asynchronous ArkTS API calls. It supports only synchronous ArkTS API calls.
130
131**System capability**: SystemCapability.Ability.AbilityRuntime.Core
132
133**Parameters**
134
135  | Name| Type| Mandatory| Description|
136  | -------- | -------- | -------- | -------- |
137  | 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.)|
138  | startMode | [StartMode](#startmode) | Yes| Start mode of the child process.|
139  | callback | AsyncCallback&lt;number&gt; | 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.|
140
141**Error codes**
142
143  For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
144
145| ID| Error Message|
146| ------- | -------- |
147| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. |
148| 16000050 | Internal error. |
149| 16000061  | Operation not supported. |
150| 16000062  | The number of child processes exceeds the upper limit. |
151
152**Example**
153
154```ts
155// Create the child process class DemoProcess.ets in src/main/ets/process of the entry module.
156// entry/src/main/ets/process/DemoProcess.ets
157import { ChildProcess } from '@kit.AbilityKit';
158
159export default class DemoProcess extends ChildProcess {
160  onStart() {
161    console.log("DemoProcess OnStart() called");
162  }
163}
164```
165
166<!--code_no_check-->
167```ts
168// Call childProcessManager.startChildProcess to start the child process.
169// entry/src/main/ets/tool/Tool.ets
170import { childProcessManager } from '@kit.AbilityKit';
171import { BusinessError } from '@kit.BasicServicesKit';
172import DemoProcess from '../process/DemoProcess';
173
174try {
175  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.
176  childProcessManager.startChildProcess("./ets/process/DemoProcess.ets", childProcessManager.StartMode.SELF_FORK, (err, data) => {
177    if (data) {
178      console.log(`startChildProcess success, pid: ${data}`);
179    } else {
180      console.error(`startChildProcess error, errorCode: ${err.code}`);
181    }
182  });
183} catch (err) {
184  console.error(`startChildProcess error, errorCode: ${(err as BusinessError).code}`);
185}
186```
187
188## childProcessManager.startArkChildProcess<sup>12+</sup>
189
190startArkChildProcess(srcEntry: string, args: ChildProcessArgs, options?: ChildProcessOptions): Promise&lt;number&gt;
191
192Starts an [ArkTS child process](../../application-models/ability-terminology.md#arkts-child-process). This API uses a promise to return the result.
193
194
195> **NOTE**
196>
197> The child process started by calling this API does not inherit the resources of the parent process. If the child process is created successfully, its PID is returned, and its [ChildProcess.onStart](js-apis-app-ability-childProcess.md#childprocessonstart) function is executed. After the function is done, the child process is not automatically destroyed. Instead, it must be destroyed by calling [process.abort](../apis-arkts/js-apis-process.md#processabort). After the process that calls this API is destroyed, the created child process is also destroyed.
198
199
200**System capability**: SystemCapability.Ability.AbilityRuntime.Core
201
202**Parameters**
203
204  | Name| Type| Mandatory| Description|
205  | -------- | -------- | -------- | -------- |
206  | 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.)|
207  | args | [ChildProcessArgs](js-apis-app-ability-childProcessArgs.md) | Yes| Parameters transferred to the child process.|
208  | options | [ChildProcessOptions](js-apis-app-ability-childProcessOptions.md) | No| Startup configuration of the child process.|
209
210**Return value**
211
212  | Type| Description|
213  | -------- | -------- |
214  | Promise&lt;number&gt; | Promise used to return the PID of the child process.|
215
216**Error codes**
217
218  For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
219
220| ID| Error Message|
221| ------- | -------- |
222| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. |
223| 801 | Capability not supported. |
224| 16000050 | Internal error. |
225| 16000061  | Operation not supported. |
226| 16000062  | The number of child processes exceeds the upper limit. |
227
228**Example**
229
230Sample code for the child process:
231
232```ts
233// Create the child process class DemoProcess.ets in src/main/ets/process of module1.
234// module1/src/main/ets/process/DemoProcess.ets
235import { ChildProcess, ChildProcessArgs } from '@kit.AbilityKit';
236
237export default class DemoProcess extends ChildProcess {
238
239  onStart(args?: ChildProcessArgs) {
240    let entryParams = args?.entryParams;
241    let fd = args?.fds?.key1;
242    // ..
243  }
244}
245```
246
247Sample 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).
248
249<!--code_no_check-->
250```ts
251// Call childProcessManager.startArkChildProcess to start the child process.
252// module1/src/main/ets/tool/Tool.ets
253import { common, ChildProcessArgs, ChildProcessOptions, childProcessManager } from '@kit.AbilityKit';
254import { fileIo } from '@kit.CoreFileKit';
255import { BusinessError } from '@kit.BasicServicesKit';
256import DemoProcess from '../process/DemoProcess';
257
258@Entry
259@Component
260struct Index {
261  build() {
262    Row() {
263      Column() {
264        Text('Click')
265          .fontSize(30)
266          .fontWeight(FontWeight.Bold)
267          .onClick(() => {
268            try {
269              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.
270              let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
271              let path = context.filesDir + "/test.txt";
272              let file = fileIo.openSync(path, fileIo.OpenMode.READ_ONLY | fileIo.OpenMode.CREATE);
273              let args: ChildProcessArgs = {
274                entryParams: "testParam",
275                fds: {
276                  "key1": file.fd
277                }
278              };
279              let options: ChildProcessOptions = {
280                isolationMode: false
281              };
282              childProcessManager.startArkChildProcess("module1/ets/process/DemoProcess.ets", args, options)
283                .then((pid) => {
284                  console.info(`startChildProcess success, pid: ${pid}`);
285                })
286                .catch((err: BusinessError) => {
287                  console.error(`startChildProcess business error, errorCode: ${err.code}, errorMsg:${err.message}`);
288                })
289            } catch (err) {
290              console.error(`startChildProcess error, errorCode: ${err.code}, errorMsg:${err.message}`);
291            }
292          });
293      }
294      .width('100%')
295    }
296    .height('100%')
297  }
298}
299```
300
301## childProcessManager.startNativeChildProcess<sup>13+</sup>
302
303startNativeChildProcess(entryPoint: string, args: ChildProcessArgs, options?: ChildProcessOptions): Promise&lt;number&gt;
304
305Starts a [native child process](../../application-models/ability-terminology.md#native-child-process). This API uses a promise to return the result.
306
307> **NOTE**
308>
309> The child process started by calling this API does not inherit the resources of the parent process. After the child process is created, its PID is returned, the dynamic link library file specified in the parameters is loaded, and the entry function of the child process is executed. Once the entry function is done, the child process is automatically destroyed. After the process that calls this API is destroyed, the created child process is also destroyed.
310
311**System capability**: SystemCapability.Ability.AbilityRuntime.Core
312
313**Parameters**
314
315  | Name| Type| Mandatory| Description|
316  | -------- | -------- | -------- | -------- |
317  | 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**.|
318  | args | [ChildProcessArgs](js-apis-app-ability-childProcessArgs.md) | Yes| Parameters transferred to the child process.|
319  | options | [ChildProcessOptions](js-apis-app-ability-childProcessOptions.md) | No| Startup configuration of the child process.|
320
321**Return value**
322
323  | Type| Description|
324  | -------- | -------- |
325  | Promise&lt;number&gt; | Promise used to return the PID of the child process.|
326
327**Error codes**
328
329  For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
330
331| ID| Error Message|
332| ------- | -------- |
333| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. |
334| 801 | Capability not supported. Failed to call the API due to limited device capabilities. |
335| 16000050 | Internal error. |
336| 16000061  | Operation not supported. |
337| 16000062  | The number of child processes exceeds the upper limit. |
338
339**Example**
340
341Sample 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).
342
343```c++
344#include <AbilityKit/native_child_process.h>
345
346extern "C" {
347
348/**
349 * Entry function of a child process, which implements the service logic of the child process.
350 * 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.
351 * After the function is returned, the child process exits.
352 */
353void Main(NativeChildProcess_Args args)
354{
355    // Obtain the input entryPrams.
356    char *entryParams = args.entryParams;
357    // Obtain the input FD list, corresponding to args.fds in ChildProcessArgs.
358    NativeChildProcess_Fd *current = args.fdList.head;
359    while (current != nullptr) {
360        char *fdName = current->fdName;
361        int32_t fd = current->fd;
362        current = current->next;
363        // Service logic
364    }
365}
366} // extern "C"
367```
368
369Sample 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).
370
371```ts
372// Main process:
373// Call childProcessManager.startNativeChildProcess to start the child process.
374import { common, ChildProcessArgs, ChildProcessOptions, childProcessManager } from '@kit.AbilityKit';
375import { fileIo } from '@kit.CoreFileKit';
376import { BusinessError } from '@kit.BasicServicesKit';
377
378@Entry
379@Component
380struct Index {
381  build() {
382    Row() {
383      Column() {
384        Text('Click')
385          .fontSize(30)
386          .fontWeight(FontWeight.Bold)
387          .onClick(() => {
388            try {
389              let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
390              let path = context.filesDir + "/test.txt";
391              let file = fileIo.openSync(path, fileIo.OpenMode.READ_ONLY | fileIo.OpenMode.CREATE);
392              let args: ChildProcessArgs = {
393                entryParams: "testParam",
394                fds: {
395                  "key1": file.fd
396                }
397              };
398              let options: ChildProcessOptions = {
399                isolationMode: false
400              };
401              childProcessManager.startNativeChildProcess("libentry.so:Main", args, options)
402                .then((pid) => {
403                  console.info(`startChildProcess success, pid: ${pid}`);
404                })
405                .catch((err: BusinessError) => {
406                  console.error(`startChildProcess business error, errorCode: ${err.code}, errorMsg:${err.message}`);
407                })
408            } catch (err) {
409              console.error(`startChildProcess error, errorCode: ${err.code}, errorMsg:${err.message}`);
410            }
411          });
412      }
413      .width('100%')
414    }
415    .height('100%')
416  }
417}
418```
419