Дочерний процесс не может получить ввод от stdin, написанный родительским процессом - PullRequest
1 голос
/ 19 июня 2019

В дочернем процессе я использую execl () для выполнения программы "test1" с вводом из stdin.Тем не менее, ввод из stdin не может быть передан в «test1», но он подходит для команды «sort».

example.c

#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
  int fds[2];                      // an array that will hold two file descriptors
  pipe(fds);                       // populates fds with two file descriptors
  pid_t pid = fork();              // create child process that is a clone of the parent

  if (pid == 0) {                  // if pid == 0, then this is the child process
    dup2(fds[0], STDIN_FILENO);    // fds[0] (the read end of pipe) donates its data to file descriptor 0
    close(fds[0]);                 // file descriptor no longer needed in child since stdin is a copy
    close(fds[1]);                 // file descriptor unused in child
    //if (execl("/usr/bin/sort", "sort", (char *)0) < 0) exit(0);//working
    if (execl("./test1", "test1", (char *)0) < 0) exit(0);//not working
  } 

  // if we reach here, we are in parent process
  close(fds[0]);                 // file descriptor unused in parent
  const char *words[] = {"pear", "peach", "apple"};
  // write input to the writable file descriptor so it can be read in from child:
  size_t numwords = sizeof(words)/sizeof(words[0]);
  for (size_t i = 0; i < numwords; i++) {
    dprintf(fds[1], "%s\n", words[i]); 
  }

  // send EOF so child can continue (child blocks until all input has been processed):
  close(fds[1]); 

  int status;
  pid_t wpid = waitpid(pid, &status, 0); // wait for child to finish before exiting
  return wpid == pid && WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}

For "команда sort ", вывод:

$ ./example
apple
peach
pear

Для" test1 "вывод:

$ ./example
hello!
test1

Если он работает для" test1 ", вывод должен быть:

$ ./test1 pear peach apple
hello!
./test1
pear
peach
apple

test1.c

#include<stdio.h> 
#include<stdlib.h> 

int main(int argc, char** argv){
  printf("hello!\n");
  for(int i = 0; i < argc; i++){
    printf("%s\n", argv[i]);
  }
  return 0;
}

Что я делаю не так?

1 Ответ

0 голосов
/ 19 июня 2019

test1 не читает никаких входных данных, поэтому передача их не работает.

Для получения выходных данных пробы test1 execl cat.

...