C and C++ can be interfaced with other languages, such as Perl and Java. In fact, the interpreters for these languages are typically written in C. C and C++ programs can be invoked from both Perl and Java using system calls. In addition, it is possible to call C / C++ functions directly in-process. Either of these options can be a good approach to providing a web user interface or a web services interface to a C / C++ program.
To invoke a C / C++ or any other executable program from Perl use
the system or exec commands. The For
example, this Perl script invokes the hello.c program above
#/usr/bin/perl -w
# Invoke the hello program as a separate process
system "./hello";
# Invoke the hello program in the same process
exec "./hello";
The system and exec commands have
similar syntax. The command in quotes is executed.
The system command launches a child process and
executes the command within that. After it completes it returns control
to the Perl process. The exec command launches the
command in the same process and after that completes does not return to
the Perl process - it exits when complete. In a web environment
you will normally use the system command.
The system command invokes a command shell if it is invoked with a single argument. If it is invoked with more than one argument then the first argument is the command to invoke and the remaining arguments are passed to that command as its arguments. This is demonstrated in the example below.
In a web environment you may want to invoke a program like this with some of the input parameters passed in based on user input. In that case someone could hack the first form by taking advantage of special characters in the UNIX shell like ; to execute their own commands. The output of this program is
In the first case the echo command is executed but in the second case it is not. It is very important for security reasons to use the second form in a web environment.
There are no user comments.
Please send ideas and opinions by email at alexamies@gmail.com.