如何在linux中获取当前进程名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9097201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:19:11  来源:igfitidea点击:

How to get current process name in linux?

clinux

提问by Mariusz

How can I get the process name in C? The same name, which is in /proc/$pid/status. I do not want to parse that file. Is there any programmatic way of doing this?

如何在 C 中获取进程名称?同名,在/proc/$pid/status. 我不想解析那个文件。有没有任何程序化的方式来做到这一点?

采纳答案by Michael Krelin - hacker

It's either pointed to by the argv[0]or indeed you can read /proc/self/status. Or you can use getenv("_"), not sure who sets that and how reliable it is.

它要么由 指向,argv[0]要么确实可以阅读/proc/self/status。或者您可以使用getenv("_"),不确定是谁设置的以及它的可靠性。

回答by Borealid

Look at the value of argv[0]which was passed to main. This should be the name under which your process was invoked.

查看argv[0]传递给的值main。这应该是调用您的流程的名称。

回答by raj_gt1

You can use __progname. However it is not better than argv[0]as it may have portability issues. But as you do not have access to argv[0]it can work as follows:-

您可以使用__progname. 然而,它并不比argv[0]它更好,因为它可能存在可移植性问题。但由于您无权访问argv[0]它,可以按如下方式工作:-

extern char *__progname;
printf("\n%s", __progname);

回答by Pierre Habouzit

If you're on using a glibc, then:

如果您使用的是 glibc,则:

#define _GNU_SOURCE
#include <errno.h>

extern char *program_invocation_name;
extern char *program_invocation_short_name;

See program_invocation_name(3)

见 program_invocation_name(3)

Under most Unices, __prognameis also defined by the libc. The sole portable way is to use argv[0]

大多数Unices下,__progname也是由libc定义的。唯一的便携方式是使用argv[0]

回答by RLT

I often make use of following call,

我经常使用以下电话,

char* currentprocname = getprogname();

回答by SIGSEGV

If you cannot access argv[] in main(), because you are implementing a library, you can have a look at my answer on a similar question here.

如果您无法在 main() 中访问 argv[],因为您正在实现一个库,您可以在此处查看我对类似问题的回答。

It basically boils down into giving you access to argc, argv[] and envp[] outside of main(). Then you could, as others have already correctly suggested, use argv[0] to retrieve the process name.

它基本上归结为让您可以访问 main() 之外的 argc、argv[] 和 envp[]。然后,正如其他人已经正确建议的那样,您可以使用 argv[0] 来检索进程名称。

回答by Ales Teska

This is a version that works on macOS, FreeBSD and Linux.

这是一个适用于 macOS、FreeBSD 和 Linux 的版本。

#if defined(__APPLE__) || defined(__FreeBSD__)
const char * appname = getprogname();
#elif defined(_GNU_SOURCE)
const char * appname = program_invocation_name;
#else
const char * appname = "?";
#endif