[pgh-pm] More shebang fun
Tom Moertel
tom at moertel.com
Wed Nov 10 22:30:02 CST 2004
Perl mongers,
Inspired by Casey's hackrifficly splendid talk tonight, I hacked up the
following alternative method for using shebang notation to run scripts
that are written in Perl-based languages. The idea is to minimize the
amount of work that we must do in C by immediately handing off to a
Perl-based handler.
The C program is tiny:
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc, char* argv[]) {
char* cmd = malloc(strlen(argv[0]) + 4);
strcat(strcpy(cmd, argv[0]), ".pl");
execv(cmd, argv);
perror("exec"); /* shouldn't get here */
return 1;
}
The C program retrieves the pathname under which it was invoked, appends
a ".pl" suffix to it, and then hands off to that program.
To use the program, we create a script handler in Perl. It runs the
actual scripts, which it receives via its first argument. Then we
create a symlink from the C program to the script handler, but leaving
off the handler's ".pl" suffix. When we write scripts in our scripting
language, we place the path to the handler -- again minus the ".pl"
suffix -- in their shebang section. That's it.
When we run a script, here's what happens. First, the shell finds the
shebang section of the script, which points to the symlink, and executes
it, thereby invoking the C program. The C program tacks a ".pl" suffix
onto the name under which it was invoked and executes that program,
thereby handing off to our Perl-based script handler. The handler
receives the path to our original script as its first argument and runs
the script.
The enclosed script shows how it all works. When the script is done,
you can "cd /tmp/shebanger" to examine the setup more closely.
Cheers,
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: shebang-test.sh
Type: application/x-sh
Size: 2100 bytes
Desc: not available
Url : http://mail.pm.org/archives/pgh-pm/attachments/20041110/6e2b6271/shebang-test.sh
More information about the pgh-pm
mailing list