How to get current process name in linux?

后端 未结 7 1811
醉话见心
醉话见心 2020-12-01 05:49

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

相关标签:
7条回答
  • 2020-12-01 05:53

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

    0 讨论(0)
  • 2020-12-01 06:02

    If you're on using a glibc, then:

    #define _GNU_SOURCE
    #include <errno.h>
    
    extern char *program_invocation_name;
    extern char *program_invocation_short_name;
    

    See program_invocation_name(3)

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

    0 讨论(0)
  • 2020-12-01 06:02

    I often make use of following call,

    char* currentprocname = getprogname();
    
    0 讨论(0)
  • 2020-12-01 06:04

    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:-

    extern char *__progname;
    printf("\n%s", __progname);
    
    0 讨论(0)
  • 2020-12-01 06:16

    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.

    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.

    0 讨论(0)
  • 2020-12-01 06:17

    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.

    0 讨论(0)
提交回复
热议问题