#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 命令空间创建一个新的进程命名空间。以下是代码的主要部分及其功能:
栈分配:
static char child_stack[STACK_SIZE];
这里我们为子进程分配了一个栈,大小为 1MB。
子进程的主函数:
int child_main(void* arg) {
printf("Child process running with PID namespace\n");
execvp(child_args[0], child_args);
return 1;
}
子进程启动后会执行这个函数,它会尝试运行 /bin/bash,从而进入一个交互式的 shell。
父进程中的 clone 调用:
int child_pid = clone(child_main, child_stack + STACK_SIZE, CLONE_NEWPID | SIGCHLD, NULL);
使用 clone 系统调用来创建一个新的子进程,并指定 CLONE_NEWPID 标志以启用新的 PID 命名空间。SIGCHLD 用于在子进程终止时通知父进程。
等待子进程结束:
wait(NULL);
父进程调用 wait 来等待子进程的结束。
通过这种方式,子进程将在一个新的 PID 命名空间中运行,其 PID 将从 1 开始,与父进程所在的命名空间隔离。
上一篇:linux poll
下一篇:linux日志查找关键字
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站