You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
How to get current process invocation name (argv[0]/$0)? (login shell on *nix) #30212
When -Login or -l is passed, this works fine (we exec /bin/sh and then exec pwsh again).
But the convention in many *nix environments for login shells is to prepend a - onto the process name when it is exec'd (e.g. bash sees its own process name as -bash and then deduces it must run login shell logic).
With PowerShell as a .NET Core 3.0 application, I don't know how to access this information.
I've tried the args in public static int Main(string[] args), Environment.GetCommandLineArgs() and Process.GetCurrentProcess():
My question is: is there a way to detect the name with which a process has been started? Ideally we could do this performantly, since it's a startup time thing and we just want to detect it as fast as possible so we can exec another process.
Reacted by TylerLeonhardt, Steve Lee and Michael Klement
changed the title [-]How to get process invocation name? (login shell on *nix)[/-][+]How to get current process invocation name? (login shell on *nix)[/+]on Jul 10, 2019
changed the title [-]How to get current process invocation name? (login shell on *nix)[/-][+]How to get current process invocation name ($0)? (login shell on *nix)[/+]on Jul 10, 2019
changed the title [-]How to get current process invocation name ($0)? (login shell on *nix)[/-][+]How to get current process invocation name (argv[0]/$0)? (login shell on *nix)[/+]on Jul 11, 2019
In case anyone else (admittedly not many others writing login shells on .NET) wants a starting point for how to do this:
privatestaticvoidDumpArgv(){intpid=getpid();if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux)){string[]argv=System.IO.File.ReadAllText($"/proc/{pid}/cmdline").Split('\0');for(inti=0;i<argv.Length;i++){Console.WriteLine($"argv[{i}]: {argv[i]}");}return;}// Get proc table sizeint[]mib=new[]{CTL_KERN,KERN_ARGMAX};intsize=sizeof(int);intmaxargs=0;unsafe{if(sysctl(mib,mib.Length,&maxargs,&size,IntPtr.Zero,0)==-1){thrownewException("argmax");}// Now read the proc tableIntPtrprocargs=Marshal.AllocHGlobal(maxargs);try{size=maxargs;mib=new[]{CTL_KERN,KERN_PROCARGS2,pid};if(sysctl(mib,mib.Length,procargs.ToPointer(),&size,IntPtr.Zero,0)==-1){thrownewException("procargs");}// Skip over argcintargc=Marshal.ReadInt32(procargs);Console.WriteLine($"argc: {argc}");byte*argvPtr=(byte*)IntPtr.Add(procargs,sizeof(int)).ToPointer();Console.WriteLine($"exec_path: {Marshal.PtrToStringAnsi((IntPtr)argvPtr)}");while(*argvPtr!=0){argvPtr++;}while(*argvPtr==0){argvPtr++;}for(inti=0;i<argc;i++){Console.WriteLine($"argv[{i}]: {Marshal.PtrToStringAnsi((IntPtr)argvPtr)}");while(*argvPtr!=0){argvPtr++;}while(*argvPtr==0){argvPtr++;}}}finally{Marshal.FreeHGlobal(procargs);}}}[DllImport("libc")]privatestaticexternintgetpid();[DllImport("libc")]privatestaticunsafeexternintsysctl(int[]mib,intmibLength,void*oldp,int*oldlenp,IntPtrnewp,intnewlenp);
int execve(const char *pathname, char *const argv[],
char *const envp[]);
argv[0] typically matches with the final part of the pathname. e.g. pathname=/bin/sh, argv[0]=sh. ProcessName gets derived from pathname (/proc/xxx/stat) and then we use argv[0] and argv[1] (/proc/xxx/cmdline) to support longer names.
In this case you want to check the argv[0], that one is -pwsh while pathname is pwsh.
We're not using cmdline as the base because if we would, scripts return their interpreter executable rather than the script name, which makes it difficult to find a specific Process using .NET APIs.
We can probably augment the cmdline reading to specifically support the login shell use-case. That is, ProcessName would then include the -.
A more generic .NET API would expose the pathname and argv array as separate properties.
@tmds I believe until we got 2 APIs it's actually more useful to get argv[0] since you can write additional logic to get it yourself while getting actual argv[0] with current solution requires native call as in above workaround.
I agree there should eventually be helper function to get user friendly name (that would be useful even for dotnet run where you most likely don't want to see dotnet path as your process) but that feels like something we could address with additional API post 3.0
it's actually more useful to get argv[0] since you can write additional logic
The current implementation of ProcessName helps users identify the correct process. There are no issues reported for this.
The login shell is the niche use-case so I'd rather have the additional logic there, than change what ProcessName is returning now.
Note that another problem with Environment.GetCommandLineArgs()[0] - apart from #11305 - is that it doesn't reflect the actual invocation path if invocation happened via a symlink, which is quite common on Unix, and it is even somewhat common for utilities to modify their behavior based on the file name of the invocation name (e.g., the tset utility applies a number of implied options when invoked via a symlink named reset)
I'm assuming that fixing the issue at hand would also fix the symlink issue - or should I open a separate one?
The division of labor would then be:
Environment.GetCommandLineArgs()[0] would report the true argv[0] / $0 invocation name, and allow shells and utilities to detect invocation conventions (- prefix) / alternate names (via symlinks) that request modified behavior.
Environment.ProcessPath (see Add Environment.ProcessPath #42768) reports the full, physical file path of the executable (as Process.GetCurrentProcess().MainModule.FileName already does).
Activity
[-]How to get process invocation name? (login shell on *nix)[/-][+]How to get current process invocation name? (login shell on *nix)[/+][-]How to get current process invocation name? (login shell on *nix)[/-][+]How to get current process invocation name ($0)? (login shell on *nix)[/+]rjmholt commentedon Jul 10, 2019
Additional output from starting PowerShell as a login shell with the
Console.WriteLines above:Note that the process is listed by
psas-pwshbutProcess.GetCurrentProcess().ProcessNameispwsh.[-]How to get current process invocation name ($0)? (login shell on *nix)[/-][+]How to get current process invocation name (argv[0]/$0)? (login shell on *nix)[/+]rjmholt commentedon Jul 11, 2019
In case anyone else (admittedly not many others writing login shells on .NET) wants a starting point for how to do this:
Based on https://gist.github.com/nonowarn/770696#file-getargv-c.
krwq commentedon Jul 17, 2019
Is this possibly related to dotnet/corefx#37294 - I have already expressed my concerns about it:
dotnet/corefx#37294 (comment)
Perhaps we should add ProcessPath now?
cc: @tmds
tmds commentedon Jul 17, 2019
execvetakes a separate pathname and argv array:argv[0]typically matches with the final part of thepathname. e.g.pathname=/bin/sh, argv[0]=sh.ProcessNamegets derived frompathname(/proc/xxx/stat) and then we useargv[0]andargv[1](/proc/xxx/cmdline) to support longer names.In this case you want to check the
argv[0], that one is-pwshwhilepathnameispwsh.We're not using
cmdlineas the base because if we would, scripts return their interpreter executable rather than the script name, which makes it difficult to find a specific Process using .NET APIs.We can probably augment the cmdline reading to specifically support the login shell use-case. That is,
ProcessNamewould then include the-.A more generic .NET API would expose the
pathnameandargvarray as separate properties.krwq commentedon Jul 17, 2019
@tmds I believe until we got 2 APIs it's actually more useful to get argv[0] since you can write additional logic to get it yourself while getting actual argv[0] with current solution requires native call as in above workaround.
I agree there should eventually be helper function to get user friendly name (that would be useful even for
dotnet runwhere you most likely don't want to see dotnet path as your process) but that feels like something we could address with additional API post 3.0tmds commentedon Jul 17, 2019
The current implementation of
ProcessNamehelps users identify the correct process. There are no issues reported for this.The login shell is the niche use-case so I'd rather have the additional logic there, than change what
ProcessNameis returning now.mklement0 commentedon Oct 16, 2020
Note that another problem with
Environment.GetCommandLineArgs()[0]- apart from #11305 - is that it doesn't reflect the actual invocation path if invocation happened via a symlink, which is quite common on Unix, and it is even somewhat common for utilities to modify their behavior based on the file name of the invocation name (e.g., thetsetutility applies a number of implied options when invoked via a symlink namedreset)I'm assuming that fixing the issue at hand would also fix the symlink issue - or should I open a separate one?
The division of labor would then be:
Environment.GetCommandLineArgs()[0]would report the true argv[0] / $0 invocation name, and allow shells and utilities to detect invocation conventions (-prefix) / alternate names (via symlinks) that request modified behavior.Environment.ProcessPath(see Add Environment.ProcessPath #42768) reports the full, physical file path of the executable (asProcess.GetCurrentProcess().MainModule.FileNamealready does).jkotas commentedon Apr 20, 2025
Duplicate of #101837