How can I execute a shell script from C in Linux?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It depends on what you want to do with the script (or any other program you want to run).
If you just want to run the script
systemis the easiest thing to do, but it does some other stuff too, including running a shell and having it run the command (/bin/sh under most *nix).If you want to either feed the shell script via its standard input or consume its standard output you can use
popen(andpclose) to set up a pipe. This also uses the shell (/bin/sh under most *nix) to run the command.Both of these are library functions that do a lot under the hood, but if they don’t meet your needs (or you just want to experiment and learn) you can also use system calls directly. This also allows you do avoid having the shell (/bin/sh) run your command for you.
The system calls of interest are
fork,execve, andwaitpid. You may want to use one of the library wrappers aroundexecve(typeman 3 execfor a list of them). You may also want to use one of the other wait functions (man 2 waithas them all). Additionally you may be interested in the system callscloneandvforkwhich are related to fork.forkduplicates the current program, where the only main difference is that the new process gets 0 returned from the call to fork. The parent process gets the new process’s process id (or an error) returned.execvereplaces the current program with a new program (keeping the same process id).waitpidis used by a parent process to wait on a particular child process to finish.Having the fork and execve steps separate allows programs to do some setup for the new process before it is created (without messing up itself). These include changing standard input, output, and stderr to be different files than the parent process used, changing the user or group of the process, closing files that the child won’t need, changing the session, or changing the environmental variables.
You may also be interested in the
pipeanddup2system calls.pipecreates a pipe (with both an input and an output file descriptor).dup2duplicates a file descriptor as a specific file descriptor (dupis similar but duplicates a file descriptor to the lowest available file descriptor).