Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 246 Vote(s) - 3.46 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to execute a shell script from C in Linux?

#1
How can I execute a shell script from C in Linux?
Reply

#2
You can use `system`:

system("/usr/local/bin/foo.sh");

This will block while executing it using `sh -c`, then return the status code.
Reply

#3
If you need more fine-grade control, you can also go the `fork` `pipe` `exec` route. This will allow your application to retrieve the data outputted from the shell script.
Reply

#4
I prefer fork + execlp for "more fine-grade" control as doron mentioned.
Example code shown below.

Store you command in a char array parameters, and malloc space for the result.


int fd[2];
pipe(fd);
if ( (childpid = fork() ) == -1){
fprintf(stderr, "FORK failed");
return 1;
} else if( childpid == 0) {
close(1);
dup2(fd[1], 1);
close(fd[0]);
execlp("/bin/sh","/bin/sh","-c",parameters,NULL);
}
wait(NULL);
read(fd[0], result, RESULT_SIZE);
printf("%s\n",result);
Reply

#5
If you're ok with POSIX, you can also use [`popen()`](

[To see links please register here]

[`pclose()`](

[To see links please register here]

)

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

int main(void) {
/* ls -al | grep '^d' */
FILE *pp;
pp = popen("ls -al", "r");
if (pp != NULL) {
while (1) {
char *line;
char buf[1000];
line = fgets(buf, sizeof buf, pp);
if (line == NULL) break;
if (line[0] == 'd') printf("%s", line); /* line includes '\n' */
}
pclose(pp);
}
return 0;
}

Reply

#6
A simple way is.....


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


#define SHELLSCRIPT "\
#/bin/bash \n\
echo \"hello\" \n\
echo \"how are you\" \n\
echo \"today\" \n\
"
/*Also you can write using char array without using MACRO*/
/*You can do split it with many strings finally concatenate
and send to the system(concatenated_string); */

int main()
{
puts("Will execute sh with the following script :");
puts(SHELLSCRIPT);
puts("Starting now:");
system(SHELLSCRIPT); //it will run the script inside the c code.
return 0;
}

Say thanks to
Yoda @<http://www.unix.com/programming/216190-putting-bash-script-c-program.html>
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through