1

If in a simple C program I am writing 4 calls to the fork() API and when I execute this program then the total processes created will be 16 on Linux.

  1. Using getpid() can get the process id of that current process.

  2. Using getppid() can get the parent process id of the calling process.

Question: How can the last child know the process id of the first process (the ancestor's parent id) from which I call the fork() API four times?

NOTE: The assumption is that all processes are running; nobody died.

psmears
  • 26,070
  • 4
  • 40
  • 48
Vinod Patidar
  • 372
  • 1
  • 4
  • 12
  • Can you please post the code? It is not clear to me what do you mean with "writing 4 times fork() ... total processes created will be 16". – terence hill Dec 11 '15 at 08:46
  • int main{ fork();fork();fork();fork();return 0;} in this condition how can we write a program to find that process id. – Vinod Patidar Dec 11 '15 at 08:46
  • I think this is the same question: http://stackoverflow.com/questions/20533979/how-to-get-all-descendent-child-process-id-of-pid-in-c-in-linux – terence hill Dec 11 '15 at 08:53
  • @VinodPatidar, please post the actual code as an exit to the question with an additional code segment. Also, that series of calls to `fork()` is a very bad idea as it does not properly handle failures, etc – user3629249 Dec 12 '15 at 12:48

2 Answers2

1

Just use

first = getpid()

before all the forks, and use that variable in the children.

psmears
  • 26,070
  • 4
  • 40
  • 48
ctrl-d
  • 392
  • 1
  • 8
0

1) You can use process tree command called ps l (for ppid seperate table is there.)

2) Using getppid() you can check recursively and reach to main process. Here you need some smart logic for this.

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222