Exec System Call For C and PHP Tutorial with Examples – POFTUT

Exec System Call For C and PHP Tutorial with Examples

exec() function is a function used to create and run processes in operating systems Linux, Windows and MacOS. exec() function has different useful variants like execve() , execl(), execlp() , execle() etc.

General Syntax

There are a lot of different exec() function variants.  Here are some of them syntax.

Example C Code

During the exec()  function example we will use following C code for examples.

Compiling C Code

In order to compile given examples and create executable we will use gcc in order to compile example source code. We assume that we will put source code to the file example.c.

And we will run created example binary like below.

Create Process with execvp() Function

execcvp() can run any binary or shell script provided as the first argument. In this example we will run binary /bin/bash .

Create Process with execv() Function

execv() function can be use to provide the executable we want to run as a process and provide parameters. In this example we will provide arguments as char array.

echo '

Create Process with execl() Function

With execl() function we can provide the execcutable and arguments directly to the function and get return code.

Create Process with execlp() Function

If we d not now the example path of the given executable we can search for it. The current environment variables will be used to search given executable file search. In this example we will search for ls command.

Create Process with execle() Function

The default behaivour of the exec functions is using default environment. But we can explicitly specify new environment variables with the  execle() function. We will use a char array pointer which will hold environment variables separated with = equal sign. In this example we will specify the HOME environment variable.

PHP exec() Function

PHP provides single exec() function which can be used directly run commands in operating system shell. In this example we will run command ls and print the output with the echo PHP statement.

Leave a Reply

Your email address will not be published. Required fields are marked *