hello every one I want to ask that I am making a program in which i have to run shell script using c program. up till now i have separated the arguments. and i have searched that exec should be use to run shell scripts
but i am totally confused as there are many variants of exec and by reading the man pages i am unable to find which is best suitable
Also in some exec function first arg is
path
and some have
pointer to file
what is the difference and what should i write in place of it.kindly guide me
thanks
Running a shell script from a C program is usually done using
#include <stdlib.h>
int system (char *s);
where s is a pointer to the pathname of the script, e.g.
int rc = system ("/home/username/bin/somescript.sh");
If you need the stdout of the script, look at the popen
man page.
#include <stdio.h>
#include <stdlib.h>
#define SHELLSCRIPT "\
for ((i=0 ; i < 10 ; i++))\n\
do\n\
echo \"Count: $i\"\n\
done\n\
"
int main(void)
{
puts("Will execute sh with the following script:");
puts(SHELLSCRIPT);
puts("Starting now:");
system(SHELLSCRIPT);
return 0;
}
Reference:
http://www.unix.com/programming/216190-putting-bash-script-c-program.html
All exec*
library functions are ultimately convenience wrappers over the execve()
system call. Just use the one that you find more convenient.
The ones that end in p
(execlp()
, execvp()
) use the $PATH
environment variable to find the program to run. For the others you need to use the full path as the first argument.
The ones ending in e
(execle()
, execve()
) allow you to define the environment (using the last argument). This way you avoid potential problems with $PATH
, $IFS
and other dangerous environment variables.
The ones wih an v
in its name take an array to specify arguments to the program to run, while the ones with an l
take the arguments to the program to run as variable arguments, ending in (char *)NULL
. As an example, execle()
is very convenient to construct a fixed invocation, while execv*
allow for a number of arguments that varies programatically.