Created
July 11, 2019 06:47
-
-
Save SteveL-MSFT/3a63aa5c8dea426a3161d4ec8ce3222a to your computer and use it in GitHub Desktop.
Get argv0
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 myps | |
{ | |
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(int pid) | |
{ | |
unsafe | |
{ | |
// 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; | |
} | |
Console.WriteLine("argc = {0}", (int)Marshal.PtrToStructure(procargs, typeof(int))); | |
// Skip over argc | |
procargs = IntPtr.Add(procargs, sizeof(int)); | |
Console.WriteLine("exec = {0}", Marshal.PtrToStringAnsi(procargs)); | |
// skip over exec path | |
while((char)Marshal.PtrToStructure(procargs, typeof(char)) != '\0') | |
{ | |
procargs = IntPtr.Add(procargs, sizeof(char)); | |
} | |
// skip trailing nulls | |
while ((char)Marshal.PtrToStructure(procargs, typeof(char)) == '\0') | |
{ | |
procargs = IntPtr.Add(procargs, sizeof(char)); | |
} | |
string argv0 = Marshal.PtrToStringAnsi(procargs); | |
Console.WriteLine("argv0 = {0}", argv0); | |
} | |
} | |
[DllImport("libc")] | |
private static unsafe extern int sysctl(int[] mib, int length, void* oldp, int* oldlenp, IntPtr newp, int newlenp); | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
GetProcArgv.PrintCurrProcArgv(int.Parse(args[0])); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment