redirect stdin when using execl

Phil Cornes pc at cs.keele.ac.uk
Fri Jun 9 00:54:15 AEST 1989


>From article <414 at sc50.UUCP>, by ron at sc50.UUCP ( Ron Winnacott ):
> Hello net.
> 
> Can anyone tell me how to redirect stdin when I use execl to 
> start a new program. The problem I am haveing is this, I am writing
> a C program that forks then execl's a new program, But I need to 
> use a redirect "<" in the execl call.
> 
> execl("/bin/mail","mail","ron","<","/tmp/tfile",NULL);
> 

The  exec() system call does not know anything about I/O redirection, that is
all dealt with by the shell. If you want to redirect the input of mail as above
then you will have to do it yourself in between your fork() call and your
execl() call, something like this:

    if (fork())
    {
        /* parent code */
    }
    else
    {
        close(0);                      /* close child input */
        open("/tmp/tfile",O_RDONLY);   /* open() takes the first available
                                           file descriptor - here 0 - so any
                                          subsequent stdin reads will come
                                          from the file /tmp/tfile */
        execl("/bin/mail","mail","ron",NULL);    /* open file descriptors are
                                                     preserved across exec() */
    }



More information about the Comp.lang.c mailing list