I have a third-party Node application that uses pipes between its child process and the parent process for communication. It uses the subprocess.stdio[3] and subprocess.stdio[4] file descriptors, instead of standard input and standard output. Relevant docs: https://nodejs.org/api/child_process.html#subprocessstdio
I created a .NET Core application, which launched as the Node app's child process. The communication works fine on Windows. It's based on the following code from SO answer:
internal class Comm : IDisposable
{
[DllImport("MSVCRT.DLL", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr _get_osfhandle(int fd);
public readonly Stream Stream;
public Comm(int fd)
{
var handle = _get_osfhandle(fd);
if (handle == IntPtr.Zero || handle == (IntPtr)(-1) || handle == (IntPtr)(-2))
{
throw new ApplicationException("invalid handle");
}
var fileHandle = new SafeFileHandle(handle, true);
Stream = new FileStream(fileHandle, FileAccess.ReadWrite);
}
public void Dispose()
{
Stream.Dispose();
}
}
Since this code is based on _get_osfhandle from MSVCRT.DLL, how can I make this class cross-platform so it works on both Windows, Linux, and macOS? What function should I import instead of _get_osfhandle?