简体   繁体   中英

Is dup2() necessary for execl

Is it necessary to replace stdin with a pipe end when using pipes?

I have an application that:-

  • Creates a pipe,
  • Forks a child process, and then
  • execl() a new process image within new child process,

But I'm running into two conceptual issues.

  1. Is it necessary to use dup() or dup2() to replace stdin ? It would obviously be easier to just use the fd from the pipe. ( I need little insight about this )

  2. If you can just use the fd from the pipe, how do you pass an integer fd using execl() when execl takes char * arguments?

I'm having trouble figuring out exactly what remains open after execl() is performed, and how to access that information from the newly execl'd process.

It depends on the commands you're running. However, many Unix commands read from standard input and write to standard output, so if the pipes are not set up so that the write end is the output of one command and the read end is the input of the next command, nothing happens (or, more accurately, programs read from places where the input isn't coming from, or write to places which will not be read from, or hang waiting for you to type the input at the terminal, or otherwise do not work as intended).

If your pipe is on file descriptors 3 and 4, the commands you execute must know to read from 3 and write to 4. You could handle that with shell, but it is moderately grotesque overkill to do so compared with using dup2() .

No; you're not obliged to use dup2() , but it is generally easier to do so. You could close standard output and then use plain dup() instead of dup2() .

If you use dup2() for a pipe, don't forget to close both of the original file descriptors.

You are probably trying to feed data to a subprocess that exists on the system but on the off chance that you are also writing the child process then no you don't need to use dup() and stdin .

execl() keeps all open file descriptors from the parent process open so you could:

int fd[2];
pipe(fd);
if (fork() == 0)
{
    char tmp[20];
    close(fd[1]);
    snprintf(tmp, sizeof(tmp), "%d", fd[0]);
    execl("client", tmp, NULL);
    exit(1);
}

and in the code for client:

int main(int argc, char** argv)
{
    int fd = strtod(argv[1], NULL, 10);
    /* Read from fd */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM