Contents
Fork

Overview

A wrapper around the fork and waitid functions.

The wrapper has two fork related functions and a set of functions used to manage child process termination.

The fork related functions are:

The child process termination management functions are:

Quick start

#include <Balau/Concurrent/Fork.hpp>

Forking

The forkSupported function can be used to verify that the platform has fork support.

The performFork function overloads take a function object (pointer, lambda) which will be run in the child process after forking. There are two types of overload.

The first overload requires a function that returns an exit status. This exit status in the child process will be returned from the function if the exitChild boolean is set to false. Otherwise, the child process will exit at the end of the call to performFork with the exit status given by the supplied function. The parent process will return the PID of the child process from the performFork function.

			/// /// Create a set of worker processes. /// ///

			// The worker state to be shared across processes.
			class WorkerState {
				// ... worker state fields ... //
			}

			using WorkerStateObject = MSharedMemoryObject<WorkerState>;
			using WorkerStatePtr = std::shared_ptr<WorkerStateObject>;

			// The worker implementation.
			class Worker {
				private: WorkerStatePtr state;

				public: Worker(WorkerStatePtr state_) : state(std::move(state_)) {}

				public: int run() {

					// ... worker loop ... //

					return 0;
				}
			};

			// Create the shared state and workers.
			WorkerStatePtr createWorkers() {
				// Create the shared state.
				auto workerState = std::make_shared<WorkerStateObject>();

				// Create the worker.
				Worker worker(sharedShared);

				std::vector<int> childProcessPids;

				// Create the child processes and run the workers within.
				for (unsigned int m = 0; m < WorkerCount; m++) {
					childProcessPids.push_back(
						Fork::performFork([&worker] () { return worker.run(); }, true)
					);
				}

				// ... Parent process continues with access to shared state ... //
				return workerState
			}

		

The second overload in the Fork class does not require a function/lambda that returns any particular type. This overload will return 0 on successful completion of the supplied function in the child process and will return zero. The parent process will again return the PID of the child process from the performFork function. It is then the responsibility of the caller to handle the continuing execution of the child process.

Termination

There are three functions available for managing child process termination.

Function name Description
waitOnProcess Wait on a process until the process terminates.
checkForTermination Check the process or processes for termination without blocking.
terminateProcess Terminate the child process if it is running.

See the Fork API documentation for more information.