The child process cannot read after exiting the parent process

After formatting and executing the child program, the execvp()parent process terminates by function . However, this causes the function to immediately return fgets()to the child process without waiting for input from stdin.

I assume that exiting the parent process will send some signals to the child process that return the function fgets(). Can someone explain me more?

Children's program code:

/* cc child.c -o child */

int main () {
  char buffer[10];
  fgets(buffer, 10, stdin);
  printf("This is what child program read:\n%s", buffer);
}

Parent program code:

/* cc parent.c -o parent */

int main (int argc, char **argv) {
  pid_t pid = fork();
  if (pid < 0) {
    perror("fork");
    exit(EXIT_FAILURE);
  }
  else if (pid == 0) {
    execvp(*(argv+1), argv+1);
  }
  else {
  //    while(1);  if while(1) or wait() is used, child process can wait for input
    exit(1);
  }
}

In the zsh shell:

zsh>: ./parent ./child
zsh>: This is what child program read:   // read nothing and print nothing
+4
source share
2 answers

. , . .

, , . , . fgets() NULL .

- , , , , , . :

$ echo test | ./parent ./child

, , .

, fgets. fgets null, feof() / ferror(), , , (stdin ) . NULL EIO.

(. , - ): fork, stdin .. , stdin, . wait(), stdin , .

+4

fgets(). , fgets NULL, .

0

Source: https://habr.com/ru/post/1527058/


All Articles