Execute and Leave

The system() function allows you to run one program from within another. If it’s your desire to launch another program and have your program quit, you can immediately follow system() with an exit() function. Or you can go out of your way and use the oddball execl() function.

I’ll admit that the execl() function isn’t common or even admired. That’s because most coders simply do this:

system("cc -v");
exit();

The above statements direct the terminal to run the command cc -v and then the current program quits. That’s pretty simple and you won’t endure any punishment for using this technique.

The execl() function very specific. It requires more setup because the function’s first argument is the command’s full pathname. On the upside, the function offers more flexibility when it comes to dealing with the command line arguments, which are specified separately.

To use the execl() function, include the unistd.h header file. Here’s the function’s argument list:

  • The first argument is the command’s full pathname.
  • The second argument is the command name. This may seem redundant, and it is.
  • The third through nth arguments are any command line options, each of which is specified separately.
  • The final argument is always a null character pointer.

Here’s a quick example:

#include <stdio.h>
#include <unistd.h>

int main()
{
    puts("Compiler Info:");
    execl("/usr/bin/cc","cc","-v",(char *)NULL);

    return(0);
}

The execl() function at Line 7 runs the cc command with the -v option. The output is version information for the system’s C compiler.

On a PC, you could use the following statement for Line 7:

    execl("C:\\MinGW\\bin\\gcc.exe","gcc","-v",(char *)NULL);

Above, I’m assuming that gcc is installed in the \MinGW\bin folder. Two backslashes are required for a Windows pathname, which is chronically stupid, but that’s Microsoft.

If Code::Blocks is installed, try using this statement instead:

    execl("C:\\Program Files (x86)\\CodeBlocks\\MinGW\\bin\\gcc.exe","gcc","-v",(char *)NULL);

Based on the complexity of the execl() statement, you can see how system() remains a far more popular alternative. In fact, the only time I would consider using execl() is when the command’s arguments must be customized. It would be easier to specify them one at a time than trying to concatenate a customized command string for the system() function.

Leave a Reply