I am trying to run a program with special standard input. I can use the file descriptor of the file, where there is something that I want to put in stdin, but I can not write directly to stdin:
$cat input.test echo Hello $
Code C:
int main(int argc, char **argv) { int fd = 0; fd = open("input.test", O_CREAT); close(STDIN_FILENO); dup2(fd, STDIN_FILENO); char *const args[] = { "bash", NULL }; execvp("bash", args); }
It works:
$./a.out Hello $
But if I try to write directly to STDIN using the program, the program does not display anything and continues to work:
int main(int argc, char **argv) { int fds[2]; pipe(fds); close(STDIN_FILENO); dup2(fds[1], STDIN_FILENO); write(fds[1], "echo Hello;", 11); // Rรฉsults are identics with fds[0] char *const args[] = { "bash", NULL }; execvp("bash", args); }
thanks for the help
Heartily, Bastien.
EDIT Problem Solved:
Thanks for your answers, here is the code that works:
int main(void) { int fd[2]; pid_t pid; if (pipe(fd) < 0) return EXIT_FAILURE; if ((pid = fork()) < 0) return EXIT_FAILURE; else if (pid != 0) { close(fd[1]); dup2(fd[0], STDIN_FILENO); execlp("bash", "bash", (char *)0); } else { close(fd[0]); write(fd[1], "echo hello\n", 11); } return EXIT_SUCCESS; }
source share