Change iostreams in child process

前端 未结 1 1725
被撕碎了的回忆
被撕碎了的回忆 2021-01-20 23:18

Right now, I\'m working on a project in which I need to start a child process to execute a new program in Linux using C++, and I need to redirect standard input and output (as i

相关标签:
1条回答
  • 2021-01-20 23:40

    You need to redirect the file descriptors 0 (standard input) and 1 (standard output) after fork() your child:

    switch (fork()) {
    case 0: {
        close(0);
        if (open(name, O_RDONLY) < 0) {
            deal_with_error();
        }
        ...
    

    You might want to open the files directed to in the parent process. Having the files readily open probably makes error handling easier. In this case you'd use dup2() to associate the correct file descriptor with the file.

    0 讨论(0)
提交回复
热议问题