Process child creating a new session

Viewed 244

I'm trying to write a program that creates a child proces. The child process creates a new session. Also, it must be verified that the child process has become the leader of the group and that it has no control terminal.

It always shows me waiting for parent to die, entered an infinite loop. What I need to change, not to display like that?

this is my code:

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>

int main(int argc, char *argv[]) {
    pid_t pid;

    if ((pid = fork()) < 0) {
        perror("fork error");
        return -1;
    } else
    if (pid == 0) {
        // Wait for the parent to die.
        while (getppid() != 1) {
            printf("Waiting for parent to die.\n");
            sleep(1);
        }

        pid = setsid();

        printf("pid, pgid and \"sid\" should be the same:\n");
        printf("pid: %d pgid: %d sid: %d\n", getpid(), getpgrp(), getsid(0));

        if ((open("/dev/tty", O_RDWR)) < 0) {
            printf("Child has no controlling terminal!\n");
        } else {
            printf("Child has a controlling terminal!\n");
        }

    } else {
        if ((open("/dev/tty", O_RDWR)) < 0) {
            printf("Parent has no controlling terminal!\n");
        } else {
            printf("Parent still has a controlling terminal!\n");
        }
        _exit(0);
    }
    return 0;
} 

1 Answers

The problem is that:

while (getppid() != 1) {
  printf("Waiting for parent to die.\n");
  sleep(1);
}

off course return always a value different to 1. For waiting the dead of the parent process, you can use wait(NULL), so you can change the block that i wrote up with:

wait(NULL)

when i execute the program with this change i receive this output:

Parent still has a controlling terminal!
pid, pgid and "sid" should be the same:
pid: 2581 pgid: 2581 sid: 2581
Child has no controlling terminal!

Is this what you need?

Related