Linux下进程切换网络命名空间后能否正常读写原TAP设备的文件描述符?
Can I read/write a TAP device's FD from a different network namespace?
Short Answer
Absolutely yes — after switching your process to network namespace ns2, you can still perform valid read() and write() operations on the file descriptor (fd) obtained for tap1 in ns1. The packets will correctly flow between your process in ns2 and the tap1 device in ns1.
Technical Background & Reasoning
Let’s break down why this works, rooted in Linux kernel behavior:
- File descriptors are namespace-agnostic: A file descriptor is a process-level handle that points to a kernel
filestructure. This structure is tied to the underlying TAP device, not the network namespace the process was in when it created the device. Switching namespaces withsetns(CLONE_NEWNET)only changes the process's network context (its view of network interfaces, routes, etc.), not the kernel objects referenced by existing file descriptors. - TUN/TAP device operation is detached from process netns: TUN/TAP devices work by maintaining kernel-level packet queues. When you call
read()on the fd, you’re pulling packets from the device’s queue;write()pushes packets into that queue. These operations don’t care which network namespace the calling process is in — they only care that the fd is valid and the device exists. setns()doesn’t alter existing resources: Thesetns()system call’s documentation clarifies that it modifies the process’s namespace context, but does not revoke or reassign access to already opened resources. Your fd fortap1remains valid regardless of subsequent netns switches.
Walkthrough of Your Code
Looking at your implementation:
get_fd_on_tap("ns1", "tap1")switches tons1, opens/dev/net/tun, and configurestap1viaTUNSETIFF. The returned fd is linked directly totap1's kernel packet queue inns1.- Back in
main(),set_ns_namespace("ns2")switches your process tons2, but the fd from step 1 stays connected totap1's queue. - The loop’s
read(fd)will fetch packets sent totap1fromns1's network stack, andwrite(fd)will inject packets intotap1, which then enterns1's network stack. None of this depends on your process being inns1.
Caveats to Keep in Mind
- Permissions: You’ll need
CAP_NET_ADMINto create the TAP device inns1, but once you have the fd, regular read/write permissions are sufficient (as long as the device still exists). - Device destruction: If
tap1is deleted inns1(e.g., viaip link delete tap1), subsequentread()/write()calls on the fd will fail with errors likeEBADForENXIO— but this is unrelated to netns switching.
内容的提问来源于stack exchange,提问作者Aythsr
相关产品推荐
相关产品推荐

