Unix to Windows Porting Dictionary for HPC

Links

Function List

dup


Unix

header file: unistd.h

int dup (int oldd);
int dup2 (int oldd, int newd);

Windows

header file: winsock2.h, Windows.h

int WSADuplicateSocket(SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFO lpProtocolInfo);
BOOL WINAPI DuplicateHandle(HANDLE hSourceProcessHandle, HANDLE hSourceHandle, HANDLE hTargetProcessHandle, LPHANDLE lpTargetHandle, DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwOptions);

Purpose

Duplicate a file descriptor/handle.

Discussion

Duplicating a Unix file descriptor, regardless of the file type, is done with either the dup() or dup2() function. Windows file handles can be duplicated using either WSADuplicateSocket() for socket handles or DuplicateHandle() for other handle types. Duplicating a file handle on Windows is more involved because of the larger number of arguments that must be prepared and passed to the Windows functions. You can place the Windows functions in helper functions if your original source code uses dup() repeatedly. There is no equivalent to the Unix dup2() function in Windows. You will need to adjust your code to handle this change. The use of dup2() usually relates to the common Unix practice of assigning a file descriptor to stdin, stdout and/or stderr which is not common practice (or practical) with Windows.

Example of Use in Windows

#include <windows.h>

HANDLE OldHandle, NewHandle;
BOOL rez;

/* OldHandle assigned earlier with an open to a file */

rez = DuplicateHandle(GetCurrentProcess(), OldHandle,
        GetCurrentProcess(), &NewHandle,
        0, FALSE, DUPLICATE_SAME_ACCESS);

if (rez == FALSE) {
        /* handle couldn't be duplicated */
        return;
}

CloseHandle(OldHandle);
/* NewHandle can still be used from this point forward */

  
blog comments powered by Disqus