Status of child job after parent is killed

Hi,

I have a requirement.

Scenario:

A parent job invokes a child job and gets killed. The child becomes orphan and gets attached to init. Child job is removed from the pid table as soon as it gets completed.
Requirement is i need the status of the child job even after the parent job is completed in the second parent job invoked if the actual parent is killed.

The only reparenting that occurs is from a dead parent to pid 1. There is no "second parent".

You will need another process that sits between the original parent and child and waits for the original child to finish and perform some IPC to inform who ever is interested that the child has died and what it's exit status is.

I don't think that you can do that. The wait and waitpid functions only work on child processes. If you try to use waitpid on any process that is not a child of the current process, it will fail. A crude example:

# cat test.c
#include<unistd.h>
#include<stdio.h>

int main() {
        fprintf(stdout,"pid: %d\n",getpid());
        sleep(1000);
}
# cat test1.c
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>

int main() {
        int procid;
        fscanf(stdin,"%d",&procid);
        if((waitpid(procid,NULL,0))==-1) {
                perror("error in waitpid!!");
        }
}
# cc test.c -o test
# cc test1.c -o test1
# ./test &
[1] 5582
# pid: 5582

# ./test1
5582
error in waitpid!!: No child processes

I think that what Porter is suggesting is a intermediate process that is the parent of the final process - a child to generate a grandchild you might say. Then when your initial process (the grandparent?) is killed you still have a process to report on the grandchild

Thank you, that is exactly what I was suggesting.

Yes, but that isn't what the OP is asking about is it? Very specifically mentions that the process is inherited by init.

And I am suggesting inserting another process between the original parent and child, so this new process is the one that gets inherited by init instead of the original child.

This new process can then be interrogated by some IPC mechanism to determine the state of the child process, write and delete pid files etc.

So instead of

/** OLD CODE **/
pid_t child=fork();

if (!child) { exit(run_child()); }

you do

/** NEW CODE **/
pid_t surrogate=fork();

    if (!surrogate)
    {
        pid_t child=fork();
        if (!child) { exit(run_child()); }
        ... do stuff to monitor child and perform IPC until told to die ... 
        exit(0);
    }

Thnx guys,

I hv used the porters method and it is working fine....