C program to execute shell script

Hi,

Can anyone give me a sample code to execute shell script from C program.

Thanks

man system
Example:
system("pwd");

Hi,

Can anyone help with the below code. I am trying to execute Shell script with arguments in C program but it is giving errors.

#include <stdlib.h>
#include <stdio.h>

int main (int argc, char *argv[])
{
 int count;
 for (count = 1; count < argc; count++)
 {
   return system("/tmp/lab5.sh ", argv[count]);
 }
 return 0;
}

In C++, you can:

#include <stdlib.h>
#include <stdio.h>
#include <string>

int main (int argc, char *argv[])
{
 int count;
 std::string cadena = "";
 std::string orden;

 for (count = 1; count < argc; count++)
 {
   cadena.append (argv[count]);
 }
 orden = "/tmp/lab5.sh " + cadena;
 return system(orden.c_str());
}

If you need C language, only you must replace the "append" operation with concatenate (strcat or sprintf) variables C char *.

In "C program to execute Shell script with arguments "thread, you can see an C++ example.

This line of code is invalid

return system("/tmp/lab5.sh ", argv[count]);

The system() API takes one argument only. Man system for more information.

Hint - create a buffer using an array or malloc(). strcpy "/tmp/lab5.sh " to buffer. strcat argv[count] to the buffer. Use buffer as argument to system API.

One more thing - you call return system() in for(). return will terminate main() immediately so you won't have your script executed argc times. I'd suggest to save the return value of system in new variable and examine it if you need error checking.