# How v2rayN CoreManager Handles Core Lifecycle for Xray, sing-box, and mihomo

> Discover how v2rayN's CoreManager effortlessly manages Xray, sing-box, and mihomo core lifecycles. Learn about initialization, configuration, and process execution for a seamless experience.

- Repository: [2dust/v2rayN](https://github.com/2dust/v2rayN)
- Tags: internals
- Published: 2026-02-27

---

**The CoreManager class orchestrates the complete lifecycle of proxy cores by initializing binaries, generating configurations, and executing processes with conditional branches that determine privilege levels based on core type, operating system, and TUN mode.**

The `CoreManager` in the 2dust/v2rayN repository serves as the central orchestration service that manages how different proxy cores—such as **Xray**, **sing-box**, and **mihomo**—are started, monitored, and terminated. Understanding how CoreManager handles the core lifecycle is essential for developers customizing proxy clients or troubleshooting connection issues across Windows, Linux, and macOS platforms.

## Initialization and Binary Preparation

The lifecycle begins with the `Init` method in [`ServiceLib/Manager/CoreManager.cs`](https://github.com/2dust/v2rayN/blob/main/ServiceLib/Manager/CoreManager.cs), which prepares the execution environment before any core can start.

```csharp
public async Task Init(Config config, Func<bool, string, Task> updateFunc)

```

This method performs two critical setup operations. First, it copies the bundled `bin` folder from the application directory to the user's storage location to ensure writeable working directories. Second, on non-Windows platforms, it iterates through all core executables and applies `chmod` permissions via `Utils.SetLinuxChmod` to guarantee the binaries can execute. See the implementation in lines **34-57** of [`CoreManager.cs`](https://github.com/2dust/v2rayN/blob/main/CoreManager.cs).

## The Core Restart Workflow

The primary entry point for switching profiles or restarting services is `LoadCore`, which functions as the orchestrated restart mechanism.

```csharp
public async Task LoadCore(ProfileItem? node)

```

This method executes a strict sequential workflow: it generates the client configuration via `CoreConfigHandler.GenerateClientConfig`, terminates any running core through `CoreStop()`, optionally removes the Windows TUN device using `WindowsUtils.RemoveTunDevice`, and then launches the new core instance. When a pre-service configuration exists, it additionally invokes `CoreStartPreService` to establish auxiliary SOCKS or TUN proxies before the main core handles traffic. The implementation spans lines **60-104** in [`ServiceLib/Manager/CoreManager.cs`](https://github.com/2dust/v2rayN/blob/main/ServiceLib/Manager/CoreManager.cs).

## Starting the Main Core Process

The `CoreStart` method handles the actual process creation for the selected profile.

```csharp
private async Task CoreStart(CoreConfigContext context)

```

This method determines the appropriate core type by calling `AppManager.Instance.GetCoreType`, retrieves the corresponding metadata from `CoreInfoManager.GetCoreInfo`, and delegates execution to the generic `RunProcess` helper. The resulting `ProcessService` instance is stored in the `_processService` field for lifecycle tracking. This logic appears in lines **79-92** of the source file.

## Handling Privileged Execution for TUN Mode

The `RunProcess` method contains the critical branching logic that differentiates standard execution from privileged operations required for TUN mode.

```csharp
private async Task<ProcessService?> RunProcess(CoreInfo? coreInfo,
                                            string configPath,
                                            bool displayLog,
                                            bool mayNeedSudo)

```

When `mayNeedSudo` is true, TUN mode is enabled in `_config.TunModeItem.EnableTun`, the core type is `sing_box` or `mihomo`, and the operating system is non-Windows, the manager delegates to `CoreAdminManager.RunProcessAsLinuxSudo`. This elevates privileges using sudo to allow network interface manipulation. For all other scenarios, it invokes `RunProcessNormal`, which constructs the argument string, injects environment variables defined in `CoreInfo`, creates a `ProcessService`, and registers the handle with `WindowsJobService` on Windows for automatic cleanup. See the privilege detection in lines **23-42** and standard execution in lines **44-81**.

## Pre-Service Configuration Management

For configurations requiring a secondary proxy layer, `CoreStartPreService` manages an auxiliary process.

```csharp
private async Task CoreStartPreService(CoreConfigContext? preContext)

```

This method executes only when the main core is already running (`_processService.HasExited == false`). It generates a separate configuration file named `CorePreConfigFileName`, defaults to the `sing_box` core type if unspecified, and stores the resulting process in `_processPreService`. The implementation resides in lines **94-112** of [`CoreManager.cs`](https://github.com/2dust/v2rayN/blob/main/CoreManager.cs).

## Stopping and Cleanup Procedures

The `CoreStop` method ensures graceful termination of all core processes.

```csharp
public async Task CoreStop()

```

If the core was launched with sudo privileges on Linux, indicated by the `_linuxSudo` flag, the method first calls `CoreAdminManager.KillProcessAsLinuxSudo` to properly terminate the elevated process. It then stops and disposes both the main `_processService` and the auxiliary `_processPreService`, finally resetting the sudo flag. This cleanup logic appears in lines **47-70**.

## Core Type Metadata and Resolution

All per-core metadata—including executable names, download URLs, command-line arguments, and environment variable mappings—resides in `CoreInfoManager`. The `GetCoreExecFile` method resolves the actual binary path for a given `ECoreType` (such as `Xray`, `sing_box`, `mihomo`, or `v2fly`), while `GetCoreInfo` provides the argument templates and execution flags required by `CoreManager`. This separation allows the lifecycle manager to handle multiple core types through a generic interface while maintaining core-specific configuration details.

## Summary

- **CoreManager** in [`ServiceLib/Manager/CoreManager.cs`](https://github.com/2dust/v2rayN/blob/main/ServiceLib/Manager/CoreManager.cs) serves as the single orchestration point for all proxy core operations in v2rayN.
- The `LoadCore` method implements the complete restart sequence: stop existing processes, generate configuration, and start new instances.
- **Privilege escalation** is handled automatically for `sing_box` and `mihomo` on Linux/macOS when TUN mode is enabled, delegating to `CoreAdminManager`.
- **Pre-service configurations** allow secondary proxy processes to run alongside the main core using `CoreStartPreService`.
- Process metadata and binary resolution are abstracted through `CoreInfoManager`, enabling support for multiple core types through the `ECoreType` enumeration.

## Frequently Asked Questions

### How does CoreManager decide which executable to run for different core types?

The manager calls `CoreInfoManager.GetCoreExecFile` within the `RunProcess` method, passing the `ECoreType` determined by `AppManager.Instance.GetCoreType`. This resolves the specific binary name (e.g., `xray`, `sing-box`, `mihomo`) based on the current operating system and architecture, returning the absolute path to the executable.

### What happens when TUN mode is enabled on Linux or macOS?

When TUN mode is enabled and the core type is `sing_box` or `mihomo`, `CoreManager.RunProcess` detects the `mayNeedSudo` condition and delegates process creation to `CoreAdminManager.RunProcessAsLinuxSudo`. This executes the core with elevated privileges required to create and manage virtual network interfaces. During shutdown, `CoreStop` calls `CoreAdminManager.KillProcessAsLinuxSudo` to terminate the privileged process.

### How does CoreManager handle configuration file generation before starting a core?

The `LoadCore` method invokes `CoreConfigHandler.GenerateClientConfig` to create the JSON or YAML configuration consumed by the core binary. For pre-service scenarios, a separate configuration file is generated with the identifier `CorePreConfigFileName` and passed to the auxiliary process launched by `CoreStartPreService`.

### What is the difference between the main core process and the pre-service process?

The main core process, stored in `_processService`, handles the primary proxy connection defined by the selected profile. The pre-service process, stored in `_processPreService`, represents an optional secondary proxy (typically SOCKS or TUN) that starts after the main core when `CoreStartPreService` detects a valid pre-service configuration context. Both processes are independently monitored and terminated during the `CoreStop` sequence.