| 371 | } |
| 372 | |
| 373 | void SC::ProcessTest::processFork() |
| 374 | { |
| 375 | //! [ProcessFork] |
| 376 | // Cross-platform lightweight clone of current process, sharing memory |
| 377 | // but keeping any modification after clone "private" (Copy-On-Write). |
| 378 | // Achieved using "fork" on Posix and "RtlCloneUserProcess" on Windows. |
| 379 | StringView sharedTag = "INITIAL"; |
| 380 | StringView parentTag = "PARENT"; |
| 381 | StringView saveFile = "ForkSaveFile.txt"; |
| 382 | |
| 383 | // The string will be duplicated using Copy-On-Write (COW) |
| 384 | String shared = sharedTag; |
| 385 | |
| 386 | // CLONE current process, starting child fork in Suspended state |
| 387 | // Forked process will be terminated by ProcessFork destructor |
| 388 | ProcessFork fork; |
| 389 | SC_TEST_EXPECT(fork.fork(ProcessFork::Suspended)); |
| 390 | |
| 391 | // After fork program must check if it's on fork or parent side |
| 392 | switch (fork.getSide()) |
| 393 | { |
| 394 | case ProcessFork::ForkChild: { |
| 395 | report.console.printLine("FORKED process"); |
| 396 | report.console.print("FORKED Shared={0}\n", shared.view()); |
| 397 | |
| 398 | // Write the "shared" memory snapshot to the file system |
| 399 | FileSystem fs; |
| 400 | SC_TEST_EXPECT(fs.init(report.applicationRootDirectory.view())); |
| 401 | SC_TEST_EXPECT(fs.writeString(saveFile, shared.view())); |
| 402 | |
| 403 | // Send (as a signal) modified string contents back to Parent |
| 404 | SC_TEST_EXPECT(fork.getWritePipe().write({shared.view().toCharSpan()})); |
| 405 | } |
| 406 | break; |
| 407 | case ProcessFork::ForkParent: { |
| 408 | report.console.printLine("PARENT process"); |
| 409 | // Check initial state to be "INITIAL" and modify shared = "PARENT" |
| 410 | report.console.print("PARENT Shared={0}\n", shared.view()); |
| 411 | SC_TEST_EXPECT(shared == sharedTag and "PARENT"); |
| 412 | shared = parentTag; |
| 413 | |
| 414 | // Resume suspended fork verifying that on its side shared == "INITIAL" |
| 415 | SC_TEST_EXPECT(fork.resumeChildFork()); |
| 416 | char string[255] = {0}; |
| 417 | Span<char> received; |
| 418 | SC_TEST_EXPECT(fork.getReadPipe().read(string, received)); |
| 419 | StringView stringFromFork(received, true, StringEncoding::Ascii); |
| 420 | report.console.print("PARENT received={0}\n", stringFromFork); |
| 421 | SC_TEST_EXPECT(stringFromFork == sharedTag); |
| 422 | |
| 423 | // Check creation of "save file" by fork and verify its content too |
| 424 | FileSystem fs; |
| 425 | SC_TEST_EXPECT(fs.init(report.applicationRootDirectory.view())); |
| 426 | String savedData = StringEncoding::Ascii; |
| 427 | SC_TEST_EXPECT(fs.read(saveFile, savedData)); |
| 428 | SC_TEST_EXPECT(savedData == sharedTag); |
| 429 | SC_TEST_EXPECT(fs.removeFile(saveFile)); |
| 430 |
nothing calls this directly
no test coverage detected