I'm trying to get the output of uname -r
in C# in .NET Core 2.2 running on Ubuntu 18.04.
I'm writing this with performance in mind, so have been trying to use a P/Invoke to achieve it.
The uname(2)
docs indicate I need to pass a struct in with the relevant sized fields. After playing with a lot of variations, I came up with:
[StructLayout(LayoutKind.Sequential)]
unsafe internal struct Utsname
{
public fixed byte sysname[65];
public fixed byte nodename[65];
public fixed byte release[65];
public fixed byte version[65];
public fixed byte machine[65];
}
public static class Main
{
[DllImport("libc.so.6", CallingConvention = CallingConvention.Cdecl)]
internal static extern int uname(ref Utsname buf);
public static void Main(string[] args)
{
byte[] bs = new byte[65];
unsafe
{
var buf = new utsname();
uname(ref buf);
Marshal.Copy((IntPtr)buf.release, bs, 0, 65);
}
Console.WriteLine(Encoding.UTF8.GetString(bs));
}
}
This seems to work, but moving it into a wrapper function like:
public static class Main
{
...
public static string GetUnameRelease()
{
var bs = new List<byte>();
unsafe
{
var buf = new utsname();
uname(ref buf);
int i = 0;
byte* p = buf.release;
while (i < 65 && *p != 0)
{
bs.Add(*p);
p++;
i++;
}
}
return Encoding.UTF8.GetString(bs.ToArray());
}
public static void Main(string[] args)
{
Console.WriteLine(GetUnameRelease());
}
}
Seems to cause it to fail. I'm just not sure what I'm doing wrong. It fails silently, presumably due to a segfault, although I'm not sure where/how to get a trace of that.
Other struct marshalling methods I've tried
I also tried a few other ways to get the struct back.
The simplest seemed to be the string
fields with fixed-length values (but I assume this fails because the caller needs to allocate mutable fields for the callee to set):
internal struct Utsname
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
public string sysname;
...
}
Or a simple byte
array:
internal struct Utsname
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 65)]
public byte[] sysname;
...
}
In this case, I assume the problem is something to do with the In/Out calling convention when passing a managed array into the call.
I tried using out
instead of ref
to simplify the P/Invoke as well, but I get the impression uname()
expects the caller to allocate the memory before the call.
I also tried using the [In]
and [Out]
attributes, but not sure what the defaults are or how using them would change things.
Writing an external C library to wrap the call
I also wrote a small C library to wrap the call to make the calling convention easier to handle:
#include <string.h>
#include <stdlib.h>
#include <sys/utsname.h>
char *get_uname_release()
{
struct utsname buf;
uname(&buf);
size_t len = strlen(buf.release);
char *release = malloc(len * sizeof(char));
strcpy(release, buf.release);
return release;
}
I compiled this with gcc -shared -o libget_uname.so -fPIC get_uname.c
and put it next to the main managed DLL.
Calling this was much easier, with just:
public static class Main
{
...
[DllImport("libget_uname.so", EntryPoint = "uname_get_release", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
internal static extern string GetUnameRelease();
}
This seemed to work every time I used it.
But I'm averse to including a native library in code, if it might be possible to just P/Invoke directly instead.
Using a Process
call instead
The other obvious simple choice would just be to call the uname
coreutil as a subprocess:
public static class Main
{
...
public static string GetUnameRelease()
{
var unameProc = new Process()
{
StartInfo = new ProcessStartInfo()
{
FileName = "uname",
Arguments = "-r",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
unameProc.Start();
unameProc.WaitForExit();
return unameProc.StandardOutput.ReadToEnd();
}
}
But I was hoping to avoid the overhead of a subprocess... Perhaps it's not so bad on Linux and just worth doing?
But I've spent a while looking into the PInvoke now, so I would like to know if it's possible.
Questions
So my questions are:
- What's the best (fastest reliable) way to get the
release
field fromuname
from C#? - How would I P/Invoke the
uname()
syscall in libc reliably to get theutsname
struct back?
strcpy
-like implementation. Following it through on the debugger, the program silently crashes at theuname(ref buf)
call. – MickensMain
method into a separate method, does that really still break things? (I can't see why just changing which method is calling it would do that.) But then I wonder if you're showing us the real code... the code you've shown doesn't compile due to a difference in casing. I would personally remove the aspects about other processes and the native library - stick to asking a very specific question. – XyleneFile.ReadAllText("/proc/sys/kernel/osrelease");
will give you the OS release – Michaud