【发布时间】:2020-04-18 00:08:55
【问题描述】:
我试图在两个 linux 命名空间中运行相同的程序。
程序需要读写文件/tmp/server.log。
所以我想确保程序A读/写server.log,但实际上它读和写/tmp/server-A.log。而对于程序B读写server.log,其实就是读写/tmp/server-B.log。
我尝试使用 mount 但没有成功...有人可以帮助我吗?或者我有没有另一种方法来提供文件隔离,这样两个程序就不会真正读/写同一个文件?
#define _GNU_SOURCE
#include<sched.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
static int child_func(void* arg) {
system("mount --bind /tmp ./a");
FILE* file;
file = fopen("/tmp/server.log","rw");
// write some log ...
return 0;
}
static int child2_func(void* arg) {
system("mount --bind /tmp ./b");
file = fopen("/tmp/server.log","rw");
// write some log....
return 0;
}
int main(int argc, char** argv) {
// Allocate stack for child task.
const int STACK_SIZE = 1 * 1024 * 1024;
char* stack = malloc(STACK_SIZE);
char* stack2 = malloc(STACK_SIZE);
if (!stack || !stack2) {
perror("malloc");
exit(1);
}
pid_t pid,pid2;
if ((pid = clone(child_func, stack + STACK_SIZE, CLONE_NEWPID | CLONE_NEWUTS | CLONE_NEWNS | CLONE_NEWNET | SIGCHLD, NULL)) == -1) {
perror("clone");
exit(1);
}
if ((pid2 = clone(child2_func, stack2 + STACK_SIZE, CLONE_NEWPID | CLONE_NEWUTS | CLONE_NEWNS | CLONE_NEWNET | SIGCHLD, NULL)) == -1) {
perror("clone");
exit(1);
}
waitpid(pid,NULL,0);
waitpid(pid2,NULL,0);
return 0;
}
更新:我根据下面回答的解决方案解决了问题!他们的解决方案对我很有帮助!
【问题讨论】:
-
这里有这么多问题,但我先从大的开始:为什么要使用Linux命名空间来解决这样一个简单的问题,而不是仅仅传递文件名作为参数写入?
-
我有点困惑。如果你想让一个子进程写入
/tmp/server-A.log,另一个写入/tmp/server-B.log,为什么不简单地设置一个变量,比如char suffix = 'A';fork第一个进程,然后设置suffix = 'B';并fork第二个,然后在每个进程使用suffix创建文件名?有很多方法可以做到这一点。如果你想要更多,那么#define SUFFIX "ABCDEFGHIJKLMNOPQRSTUVWXYZ",然后保持一个计数器和循环分叉SUFFIX[n++],或类似的东西。 -
我相信也有 mount 系统调用,不需要用 system() 调用 shell:man7.org/linux/man-pages/man2/mount.2.html
-
child_func其实是在调用python脚本,我无法修改python脚本来指定写入路径,我这里只是用一个简单的函数来演示一下@JosephSible-ReinstateMonica的案例跨度>
-
@David C. Rankin 我做不到,我只是写了这个愚蠢的函数来显示我需要做什么
标签: c linux linux-namespaces