how do I exec() a script

Conor P. Cahill cpcahil at virtech.uucp
Thu Jun 28 08:50:15 AEST 1990


In article <661 at kps.UUCP> llj at kps.se (Leif Ljung /DP) writes:
>I have a program that I want to do a general exec(2) sometimes
>executing a binary program, sometimes a shell-script preferably
>using PATH.
>Say I have the program `prog' - if this is a script I add the
>'#! /bin/sh' at the top. Can I exec(2) that? No.

The correct way to do this (one that will work on systems that understand
the "#!" and those that don't) is as follows:

	place "#!/bin/sh" as the first line for the program.

	in the code that you wish to exec the program do the following:


		execvp("prog",argv);  /* argv is setup accordingly */

		/*
		 * if we get here, prog was not executed by the kernel,
		 * so this system doesn't understand "#!" and we must call
		 * the shell ourselves
		 */

		arg_str[0] = '\0';	
		for(i=0; argv[i] != NULL; i++)
			strcat(arg_str,argv[i]);

		sh_argv[0] = "sh";
		sh_argv[1] = "-c";
		sh_argv[2] = arg_str;
		sh_argv[3] = (char *)0;
		execvp("sh",sh_argv);

-c is used so sh will use PATH to find the program.

NOTE: I did not compile or test the above code, your milage may vary.


-- 
Conor P. Cahill            (703)430-9247        Virtual Technologies, Inc.,
uunet!virtech!cpcahil                           46030 Manekin Plaza, Suite 160
                                                Sterling, VA 22170 



More information about the Comp.lang.c mailing list