0

I am executing a really simple program which takes input in integer from user using scanf. I execute this program as a child program via fork() and execv.The child program never takes input from user.Any help would be appreciated.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    pid_t childpid;

    if((childpid = fork()) == -1)
    {
        perror("fork");
        exit(1);
    }

    if(childpid == 0)
    {
        execv("child",NULL);
        exit(1);
    }
    else  
    {
        printf("Parent process is terminating...\n");
        return 0;
    }
}

and the child code is

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    int temp;
    printf("This is Child Process. Child is going to sleep for 5 seconds\n");
    sleep(5);
    printf("Please enter an integer to terminate the process ");
    scanf("%d",&temp);
    printf("You entered %d ",temp);
    printf("Child terminated");
    return 0;
}

OUTPUT

[@localhost cascading]$ ./cascading 
Parent process is terminating...
[@localhost cascading]$ This is Child Process. Child is going to sleep for 5 seconds
Please enter an integer to terminate the process You entered 12435[@localhost cascading]$ ^C
[@localhost cascading]$ 

I am running the code in fedora installed on a virtual machine.Thanks

Krekkon
  • 1,349
  • 14
  • 35

2 Answers2

2

Once the parent process finishes, control is returned to shell; and stdin could be closed.

To retain child's access to stdin, you can let the parent wait until the child is done.

So, in your parent:

else {
    printf("Parent process is terminating...\n");
    wait(NULL);
    return 0;
}
Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34
  • Actually i wrote this code for showing how fedora does not support cascading termination by showing that child can execute without parent. – user3422997 Mar 16 '14 at 11:03
0

You need to wait for child process to be finished, please modify your code like this

if(childpid == 0)
{
    execv("child",NULL);
    exit(1);
}
else
{
    wait(); //wait for child
    printf("Parent process is terminating...\n");
    return 0;
}
Rahul R Dhobi
  • 5,668
  • 1
  • 29
  • 38