__clone2 - Linux


Overview

__clone2 is an advanced Linux command that creates a new thread or process with flexible options for sharing resources, inheriting attributes, and setting flags. It enables fine-grained control over process duplication, providing a powerful tool for operating system research, virtualization, and performance optimization.

Syntax

__clone2(flags, stack_addr, stack_size, parent_tid, tls, child_tid)

Options/Flags

| Flag | Effect | Default |
|—|—|—|
| CLONE_PARENT | Inherit process attributes from parent process | No |
| CLONE_CHILD_CLEARTID | Clear child thread ID on exit | No |
| CLONE_DETACHED | Don’t pass signals from parent to child | No |
| CLONE_FILES | Share open file descriptors with parent | Yes |
| CLONE_FS | Share file system information with parent | Yes |
| CLONE_IO | Share I/O resources with parent | Yes |
| CLONE_NEWCGROUP | Create a new cgroup namespace | No |
| CLONE_NEWIPC | Create a new IPC namespace | No |
| CLONE_NEWNET | Create a new network namespace | No |
| CLONE_NEWNS | Create a new mount namespace | No |
| CLONE_NEWPID | Create a new PID namespace | No |
| CLONE_NEWUUTS | Create a new UTS namespace | No |
| CLONE_NEWUSER | Create a new user namespace | No |
| CLONE_VM | Share virtual memory with parent | Yes |
| CLONE_THREAD | Create a new thread instead of a process | No |

Examples

Create a new thread

clone2(CLONE_THREAD);

Create a new process with shared memory and file descriptors

clone2(CLONE_FILES | CLONE_VM, NULL, 0);

Create a new process in a new network namespace

clone2(CLONE_NEWNET);

Common Issues

  • Ensure that the flags passed to __clone2 are compatible and don’t conflict.
  • If creating a new thread, the stack size must be large enough to accommodate the thread’s stack.
  • Memory areas shared between the parent and child processes should be protected from concurrent access to prevent corruption.

Integration

  • __clone2 can be combined with __fork or __vfork to create new processes with specific resource sharing configurations.
  • It can be used in conjunction with __setns to move processes between namespaces.

Related Commands

  • __fork
  • __vfork
  • __setns