0

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

2
  • exec will replace your current program with the script. If you want your program to continue to run you should use system for synchronous execution and fork + exec for asynchronous execution. Commented Oct 11, 2011 at 10:51
  • Whether to choose execve or another function from the exec family depends on whether you want/need to use the path, pass in a list of environment variables, etc. If you don't, pick the simplest. Commented Oct 11, 2011 at 19:43

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1
#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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.