Wednesday, June 13, 2012
6:09 PM

Using execve

execve() is a function used to launch a process from with in another process.

The sytax of the function is :



Arguments:



The executable pointed to by "filename" replaces the current process. The function execve never returns to the calling function unless there is an error in executing the executable.

For example:

Let us write a program to print hello world and try to execute this from another program using execve.

hello.c



execve.c:



In the above program we are calling an executable "hello" and passig no arguments to it. We said that the execve never returns to the calling function if there is no error, to confirm this we have added a print statement after execve which should not get printed if the call is successful.

Now compile both the programs, make sure that the executable of hello.c is named as hello.



Execute the execve



Output:



Passing arguments:

To pass arguments in execve, we can make use of the second argument which is a pointer to an array of pointers.

For example



Let us modify the above hello.c to accept these arguments



execve.c



Compile and execute them as shown above and we should see the output



But the standard convention is to always pass the executable itself as the first argument and only then pass the other arguments. Thus to follow the convention we can modify the code as below.



execve.c





Executing a script

execve can also be used to run scripts that start with the line #! pointing to an interpreter.

For example

script.sh



save the script as sys.sh and give it execute permissions.





Compile and execute the program execve.c and we should see the output




0 comments:

Post a Comment