子进程无法从父进程编写的stdin获取输入

时间:2019-06-19 12:37:26

标签: linux pipe fork dup2

在子进程中,我使用execl()从stdin的输入执行程序“ test1”。但是,不能将来自stdin的输入传递给“ test1”,但对于“ sort”命令来说是可以的。

示例。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;
}

对于“ 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 :(得分:0)

test1不会读取任何输入,因此传递输入无效。

要获得示例输出,请使用test1 execl cat。