0

I read that only parent gets the Process id of child after executing fork command and we can't access the process id of parent from child,to achieve that we need to use pipes for transferring process Id from parent to child.

My doubt is can't we directly use getppid() in child process to get parent process id ? Why will it not work

  • 1
    You are basing the question on the premise that getppid() does not work. What justification do you have for that premise? – JdeBP Sep 5 '17 at 5:47
  • By not working I mean that getppid() in child is always returning 0 but parent process ID is non zero. – Zephyr Sep 5 '17 at 5:49
2

Under Linux, you can simply check the kernel's process info:

grep ^PPid: /proc/12345/status

where 12345 is the PID of the child.

To find the parent of a shell do

grep ^PPid: /proc/$$/status
  • I am actually trying this with C program. After calling fork() function, I am not able to get parent process ID using getppid() function, although getpid() works. I don't understand the reason behind this. – Zephyr Sep 5 '17 at 5:41
  • 1
    @Zephyr That is very strange (unless PID namespaces are involved). You should ask this on Stackoverflow. – Hauke Laging Sep 5 '17 at 5:47
  • @Zephyr There's an error in your code. You can ask about this on Stack Overflow, but remember to post your code. – Gilles Sep 5 '17 at 22:06
2

Your premise is false. A process can always obtain the process ID of its parent by calling getppid. getppid is one of the rare system calls that cannot fail. Even if the process's original parent process has died, the child gets adopted by init, so getppid will return 1.

A process can't find the PIDs of its children, or the PID of its grandparent, or the PIDs of it siblings, etc. To be precise, it can find out, but only by calling ps or some equivalent method such as collecting information from /proc, i.e. the same methods that any unrelated process can use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.