CopyFileHandle: API Reference, Syntax, and Code Examples The CopyFileHandle API is a core utility designed for high-performance file manipulation. It allows developers to duplicate, transfer, or mirror file descriptors and handles within backend systems. This reference covers its syntax, parameters, and practical implementation examples. API Overview
CopyFileHandle duplicates an existing file handle. It creates a new reference pointing to the same underlying file resource. This enables safe concurrent file operations, privilege separation, and stream redirection without reopening the physical file. Key Features
Zero-Copy Architecture: Duplicates references without copying the actual file data.
Asynchronous Support: Integrates with non-blocking I/O lifecycles.
Cross-Process Sharing: Enables safe passing of file handles between parent and child processes. Syntax and Parameters
FileHandle CopyFileHandle(sourceHandle, flags, securityAttributes) Use code with caution. Parameters sourceHandle (Required) Type: Integer / Object
Description: The valid identifier of the source file to copy. flags (Optional) Type: Bitmask / Enum
Description: Configuration options for access rights (e.g., Read-Only, Inherit, Close-on-Exec). securityAttributes (Optional) Type: Pointer / Object
Description: Defines inheritance rules and access permissions for the new handle. Return Value
Success: Returns a new, independent FileHandle object or pointer.
Failure: Throws an exception or returns null/-1 depending on the language runtime. Code Examples 1. Node.js (Asynchronous Reference Duplication)
In modern JavaScript environments, duplicating file handles prevents resource locks during heavy I/O operations. javascript
import { open } from ‘fs/promises’; async function duplicateLogHandle(filePath) { let originalHandle; let copiedHandle; try { // Open the original file handle originalHandle = await open(filePath, ‘r+’); // Duplicate the handle using the internal API structure copiedHandle = await originalHandle.duplicate(); console.log(Original FD: ${originalHandle.fd}, Copied FD: ${copiedHandle.fd}); return copiedHandle; } catch (error) { console.error(‘Failed to copy file handle:’, error); } finally { if (originalHandle) await originalHandle.close(); } } Use code with caution. 2. C++ / Win32 (System-Level DuplicateHandle)
Low-level systems require explicit permission management when duplicating handles across threads or processes.
#include #include HANDLE MirrorFileHandle(HANDLE hSourceProcess, HANDLE hSourceHandle) { HANDLE hTargetHandle = INVALID_HANDLE_VALUE; BOOL result = DuplicateHandle( hSourceProcess, // Source process handle hSourceHandle, // Handle to duplicate GetCurrentProcess(), // Target process handle &hTargetHandle, // Pointer to the new handle 0, // Desired access (ignored with same_access flag) FALSE, // Inherit handle flag DUPLICATE_SAME_ACCESS // Options flag ); if (!result) { std::cerr << “Handle duplication failed. Error: ” << GetLastError() << std::endl; return INVALID_HANDLE_VALUE; } return hTargetHandle; } Use code with caution. 3. Python (POSIX File Descriptor Duplication)
Python leverages low-level OS primitives to clone file descriptors safely.
import os def clone_file_descriptor(file_path): try: # Open original file file_descriptor = os.open(file_path, os.O_RDWR | os.O_CREAT) # Duplicate the file handle / descriptor cloned_descriptor = os.dup(file_descriptor) print(print(f”Original FD: {file_descriptor}, Cloned FD: {cloned_descriptor}“)) return cloned_descriptor except OSError as e: print(f”Error duplicating handle: {e}“) finally: # Clean up original descriptor if needed if ‘file_descriptor’ in locals(): os.close(file_descriptor) Use code with caution. Error Handling and Best Practices Track Handle Lifecycles
Explicit Closures: Always close the copied handle independently of the source handle.
Leak Prevention: Failing to release copied handles causes system resource leaks and file locking issues. Common Error Codes Error Code Resolution ERROR_INVALID_HANDLE The source handle is closed or corrupt. Verify file initialization before copying. ERROR_ACCESS_DENIED Insufficient system permissions. Elevate execution rights or adjust safety flags. ERROR_TOO_MANY_OPEN_FILES Process descriptor limit reached. Implement strict handle closing logic. To help refine this guide, tell me:
What programming language or operating system is your primary target?
Is this for a specific framework or runtime (like .NET, Win32, or POSIX)? Do you need cross-process architecture patterns? Saved time Comprehensive Inappropriate Not working
A copy of this chat, including the images and video, will be included with your feedback A copy of this chat will be included with your feedback
Your feedback will include a copy of this chat and the image from your search
Your feedback will include a copy of this chat, any links you shared, and the image from your search.
Thanks for letting us know
Google may use account and system data to understand your feedback and improve our services, subject to our Privacy Policy and Terms of Service. For legal issues, make a legal removal request.