João Pimentel
João Pimentel

Reputation: 51

Get child of child using fork()

I'm having some trouble on my Operating Systems class. I need to write a function in C where each child generates another child, and every parent can only have one child. I also have to print their pid's.

This is what I have so far:

#define MAX_COUNT 10

pid_t ex5_1 (pid_t pid) {
    pid = fork();
    if (!pid) {
        printf("ID %d Parent %d \n", getpid(), getppid());
        _exit(1);   
    }
    return pid;
}
void ex5 () {
     pid_t  pid;
     int    i;
     pid = fork();
     for (i = 1; i <= MAX_COUNT; i++) {
          pid = ex5_1(pid);
          int status;
          wait(&status);
     } 
}

I would be very grateful if anyone can help!

Upvotes: 1

Views: 1241

Answers (1)

Mickael B.
Mickael B.

Reputation: 5215

Here is what the man says about fork :

On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.

So you just have to check the return of fork like this :

int pid = fork();
if (pid < 0)
    // error handling here
else if (pid == 0)
    // here you are in the child
else
    // here you are in the parent

At the end, to create a child in a child, you can do something like this :

void child(int i)
{
    int pid;

    printf("Child number %d, ID %d Parent %d \n", i,  getpid(), getppid());
    if (i == MAX)
        return;
    pid = fork();
    if (pid < 0)
        // error handling here
    else if (pid == 0)
        child(++i);
    else
        waitpid(pid, null, 0);
    exit(0);
}

int main() {
    int i = 0;  
    int pid = fork();
    if (pid < 0)
        // error handling here
    else if (pid == 0)
        child(++i);
    else
        waitpid(pid, null, 0);
}

Upvotes: 2

Related Questions