Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

linux namespace

作者:涅盘の梦   发布日期:2026-07-13   浏览:13

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sched.h>
#include <signal.h>

#define STACK_SIZE (1024 * 1024)

static char child_stack[STACK_SIZE];

char* const child_args[] = {
    "/bin/bash",
    NULL
};

int child_main(void* arg) {
    printf("Child process running with PID namespace\n");
    execvp(child_args[0], child_args);
    return 1;
}

int main() {
    printf("Parent process starting\n");

    int child_pid = clone(child_main, child_stack + STACK_SIZE, CLONE_NEWPID | SIGCHLD, NULL);

    if (child_pid == -1) {
        perror("clone");
        exit(EXIT_FAILURE);
    }

    printf("Child process created with PID: %d\n", child_pid);

    wait(NULL);

    printf("Child process terminated\n");

    return 0;
}

解释说明

这段代码展示了如何使用 Linux 的 CLONE_NEWPID 命令空间创建一个新的进程命名空间。以下是代码的主要部分及其功能:

  1. 栈分配

    static char child_stack[STACK_SIZE];

    这里我们为子进程分配了一个栈,大小为 1MB。

  2. 子进程的主函数

    int child_main(void* arg) {
        printf("Child process running with PID namespace\n");
        execvp(child_args[0], child_args);
        return 1;
    }

    子进程启动后会执行这个函数,它会尝试运行 /bin/bash,从而进入一个交互式的 shell。

  3. 父进程中的 clone 调用

    int child_pid = clone(child_main, child_stack + STACK_SIZE, CLONE_NEWPID | SIGCHLD, NULL);

    使用 clone 系统调用来创建一个新的子进程,并指定 CLONE_NEWPID 标志以启用新的 PID 命名空间。SIGCHLD 用于在子进程终止时通知父进程。

  4. 等待子进程结束

    wait(NULL);

    父进程调用 wait 来等待子进程的结束。

通过这种方式,子进程将在一个新的 PID 命名空间中运行,其 PID 将从 1 开始,与父进程所在的命名空间隔离。

上一篇:linux poll

下一篇:linux日志查找关键字

大家都在看

linux如何启动nginx

linux常用命令查询端口是否正常

linux 发送邮件

linux长ping命令

linux groupadd

linux关机命令行

linux 安装 gcc

linux重启oracle命令

linux把一个文件夹移动到另一个文件夹里

linux查看系统运行时间

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站