redirect stdin when using execl

Dave Jones djones at megatest.UUCP
Sat Jun 10 08:31:11 AEST 1989


> In article <414 at sc50.UUCP> ron at sc50.UUCP ( Ron Winnacott ) writes:
>>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.
>>

Under BSD Unix, you use dup2. 

(All you folks who want only to see complete, production quality,
 QA-tested code, wine-soaked and sugar-cured, shut your eyes quick!)



It goes something like this:

if((pid = fork()) == 0)
   { 
         /* This the the spawned process. */
         int file_descriptor = open("foo/bar", "r");

         if(file_descriptor == -1)
	   {
	     perror("foo/bar");
	     _exit(-1);
	   }
	 else
	   { 
	      dup2(file_descriptor,0); /* make it the standard input */
              close(file_descriptor);

	      /* Here, close any of the parent process's file-descriptors that
               * will not be used by this process..
               */

	      /* and now... */
              execl("prog", "arg0", /* etc */ (char*)0);

	      /* It's an error if we get to here.... */
              /* etc.. */
	      _exit(-1);
	   }
    }
else
    { if(pid != -1)
         { /* provide for "reaping" the process. */
           /* See man page for "wait" */
         }
      else
         { /* Could not execl the program... */
         }
    }



More information about the Comp.lang.c mailing list