0

I`ll be glad to get an explanation how unshar mount namespace works for the following code:

unshare (mount_ns)
int pid = fork()
if (pid ==0)
{
   makedir("myDir");
   mount("path", "myDir", 0);
   int fd = open("myDir/myFile.txt", O_CREATE|O_RDWR);
   
   wrte(fd, "123\n",4);
   close(fd);
}
sleep(100000);
if(pid == 0)
{
   if (open("myDir/myFile.txt", O_RDONLY) < 0)
      printf ("son proc failed to read file\n");
   else
      printf ("son proc ok to read file\n");
}
else
{
    if (open("myDir/myFile.txt", O_RDONLY) < 0)
      printf ("parent proc failed to read file\n");
   else
      printf ("parent proc failed to read file\n");
}

I expected to see son proc ok to read file, parent proc failed to read file but both success. How can it be after unshare?

YAKOVM
  • 9,805
  • 31
  • 116
  • 217

1 Answers1

0

I assume its a C code. There seems to be multiple mistakes in the code that you provided.

First of all, you would not realize that parent success to read the file because:

if (open("myDir/myFile.txt", O_RDONLY) < 0)
  printf ("parent proc failed to read file\n");
else
  printf ("parent proc failed to read file\n");

should be

if (open("myDir/myFile.txt", O_RDONLY) < 0)
  printf ("parent proc failed to read file\n");
else
  printf ("parent proc ok to read file\n");

Moreover, maybe the following:

int fd = open("myDir/myFile.txt", O_CREATE|O_RDWR);
wrte(fd, "123\n",4);

should be:

int fd = open("myDir/myFile.txt", O_CREAT|O_RDWR);
write(fd, "123\n",4);

Additionnally:

If you unshare your mount namespace BEFORE the fork, you will expect both parent and child belonging to the same mount namespace.

Maybe you should move the 'unshare (mount_ns)' somewhere else like this:

int pid = fork()
if (pid ==0) {
  unshare (mount_ns)
  makedir("myDir");
  ...

Best regards.