title: How to create multiple network namespace from a single process instance
body: <p>I am using following C function to create <strong>multiple network namespaces</strong> from a <strong>single process instance</strong>:</p>
  
  <pre><code>void create_namespace(const char *ns_name)
  {
      char ns_path[100];
  
      snprintf(ns_path, 100, "%s/%s", "/var/run/netns", ns_name);
      close(open(ns_path, O_RDONLY|O_CREAT|O_EXCL, 0));
      unshare(CLONE_NEWNET);
      mount("/proc/self/ns/net", ns_path, "none", MS_BIND , NULL);
  }
  </code></pre>
  
  <p>After my process creates all the namspaces and I add a <em>tap</em> interface to any of the one network namespace (with <code>ip link set tap1 netns ns1</code> command), then I actually see this interface in all of the namespaces (presumably, this is actually a single namespace that goes under different names).</p>
  
  <p>But, if I create multiple namespaces by using multiple processes, then everything is working just fine.</p>
  
  <p>What could be wrong here? Do I have to pass any additional flags to the <code>unshare()</code> to get this working from a single process instance? Is there a limitation that a single process instance can't create multiple network namespaces? Or is there a problem with <code>mount()</code> call, because <code>/proc/self/ns/net</code> is actually mounted multiple times?</p>
  
  <p><strong>Update:</strong>
  It seems that <code>unshare()</code> function creates multiple network namespaces correctly, but all the mount points in <code>/var/run/netns/</code> actually reference to the first network namespace that was mounted in that direcotry.</p>
  
  <p><strong>Update2:</strong>
  It seems that the best approach is to fork() another process and execute create_namespace() function from there. Anyway, I would be glad to hear a better solution that does not involve fork() call or at least get a confirmation that would prove that it is impossible to create and manage multiple network namespaces from a single process.</p>
  
  <p><strong>Update3:</strong>
  I am able to create multiple namespaces with unshare() by using the following code:</p>
  
  <pre><code>int  main() {
      create_namespace("a");
      system("ip tuntap add mode tap tapa");
      system("ifconfig -a");//shows lo and tapA interface
      create_namespace("b");
      system("ip tuntap add mode tap tapb");
      system("ifconfig -a");//show lo and tapB interface, but does not show tapA. So this is second namespace created.
  }
  </code></pre>
  
  <p>But after the process terminates and I execute <code>ip netns exec a ifconfig -a</code> and <code>ip netns exec b ifconfig -a</code> it seems that both commands were suddenly executed in namespace <em>a</em>. So the actual problem is storing the references to the namespaces (or calling mount() the right way. But I am not sure, if this is possible).</p>