0

I am running two instances of a program called SMU, hence there will be two separate processes with the same name SMU. And each SMU process will create one (can be more than 1) child process, hence now there will be 4 process with the same process name as shown below (where 22313, 23835 are parent processes of two different instances).

22313 pts/10   00:35:00 SMU
22314 pts/10   00:35:06 SMU
23835 pts/6    00:25:02 SMU
23836 pts/6    00:24:56 SMU

I want to write a separate C code where i want to create one linked list per one instance of SMU to list all the PIDs of that process tree.
So I need know how can i find how many instances are running?, how to find PIDs with the same name?, which process is belongs to which process group and whether the process is Child or Parent?.

Are there any C APIs to do the job for me, and If I have to use pstree, how can I use it to meet my requirement.

1 Answer 1

2

Trying to parse the output of a user-facing command usually becomes the most fragile part of your program, by a large margin. (Especially something as complex as pstree output.) The output is meant for humans and is not suitable for computer consumption. It can change between program versions, or depending on system locale (date, language, character set), or depending on the user's local customizations. Do not parse pstree.

On Linux, the main method to enumerate processes – the source of this information – is listing subdirectories of /proc with numeric-only names. Each such directory represents a process and its name is the PID. Its parent can be determined by reading /proc/<pid>/status and looking for the PPid: attribute (alongside Pid: itself).

To do this more conveniently, you can use one of the APIs provided by libprocps: new APIprocps_proctab_read(), or old APIreadproc(), readproctab3().

To manage multiple instances of a service, use a service manager. Most Linux systems include one (called systemd). It automatically keeps track of which processes belong to which service, so that commands like systemctl restart smu@foo (as well as the corresponding C APIs) always choose the right PIDs.

3
  • Thank you for the answer, but I could not find any man pages for these APIs though the ~libprocps~ is installed in my system, can I know how to use them
    – reddi hari
    Oct 16, 2018 at 9:39
  • The old API has no docs; and unfortunately what I thought was the docs for 'new API' appears to be only a future plan for one. So you're back to manually digging through /proc, it would seem. Oct 16, 2018 at 9:54
  • is it a good plan to read each status file of each process directory in the /proc and look for the string SMU, so that I get all the info I need
    – reddi hari
    Oct 16, 2018 at 11:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .