running shell script using c programming

前端 未结 3 1818
北海茫月
北海茫月 2021-01-25 23:56

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 tha

相关标签:
3条回答
  • 2021-01-26 00:05
    #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

    0 讨论(0)
  • 2021-01-26 00:19

    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.

    0 讨论(0)
  • 2021-01-26 00:21

    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.

    0 讨论(0)
提交回复
热议问题