Created
July 11, 2019 03:13
-
-
Save rjmholt/ea0003c2ba3871fcf85fac79b4a3e9ed to your computer and use it in GitHub Desktop.
Get current process invocation name on macOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
namespace CSharpPlayground | |
{ | |
public static class GetProcArgv | |
{ | |
private const int CTL_KERN = 1; | |
private const int KERN_ARGMAX = 8; | |
private const int KERN_PROCARGS2 = 49; | |
public static void PrintCurrProcArgv() | |
{ | |
unsafe | |
{ | |
// Get current process pid | |
int pid = getpid(); | |
// Get proc table size | |
int[] mib = new [] { CTL_KERN, KERN_ARGMAX }; | |
int size = sizeof(int); | |
int maxargs = 0; | |
if (sysctl(mib, mib.Length, &maxargs, &size, IntPtr.Zero, 0) == -1) | |
{ | |
Console.Error.WriteLine("argmax"); | |
return; | |
} | |
// Now read the proc table | |
IntPtr procargs = Marshal.AllocHGlobal(maxargs); | |
size = maxargs; | |
mib = new [] { CTL_KERN, KERN_PROCARGS2, pid }; | |
if (sysctl(mib, mib.Length, procargs.ToPointer(), &size, IntPtr.Zero, 0) == -1) | |
{ | |
Console.Error.WriteLine("procargs"); | |
return; | |
} | |
// Skip over argc | |
IntPtr argv0Ptr = IntPtr.Add(procargs, sizeof(int)); | |
string argv0 = Marshal.PtrToStringAnsi(argv0Ptr); | |
Console.WriteLine(argv0); | |
} | |
} | |
[DllImport("libc")] | |
private static extern int getpid(); | |
[DllImport("libc")] | |
private static unsafe extern int sysctl(int[] mib, int length, void* oldp, int* oldlenp, IntPtr newp, int newlenp); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment