开发者

Process tree, how to find if a said process is the root one?

开发者 https://www.devze.com 2023-02-25 19:33 出处:网络
I have a directory monit开发者_JAVA百科oring application which works recursively by launching new processes.

I have a directory monit开发者_JAVA百科oring application which works recursively by launching new processes.

I'd like to know if I'm the "root" process in this tree. I thought about trying to get the name of the caller process and check if it's the same as argv[0].

Is there a smarter way of doing this? Keep in mind, this is a Linux app.

Keep in mind, I don't have much time for this and I'm but a student, so a simple solution would be great.

Thanks for your time.


If you use fork() to create new processes, you can have a local variable initially set at zero that each child sets to 1 immediately after forking. Only the root process would still have it set at zero after a fork.

You could even increase it after each fork, which would let you know how deep in your process tree each process is.

EDIT:

If you cannot use this (e.g. because you do an exec() after fork), you can use any of the common ways that shells use to pass information to the programs that you launch:

  • Environment variables: call setenv() after fork() but before exec() - or add it in the environment when calling exec().

  • Use a special command line argument.

  • Use a special value for argv[0] when doing exec().


Have you the possibility to add an argument meaning "I'm not the root"? That seems the simplest approach.


If you are calling exec, add a special argument, or environment variable called "I_AM_NOT_THE_ROOT" which the child processes get, but the parent does not.

I recently used a command-line argument for this, but env variables might be more convenient.

0

精彩评论

暂无评论...
验证码 换一张
取 消