As the title says, I have a string which contains a bash command given by input(for example, command="ls -l") and I need to execute it from a C program. I know I could simply use system(command), but it's a school exercise and I can't use system, nor popen. I thought about using exec*, but it would require to parse the string to separate the command and the various parameters. Is there a system call (not system) which allows me to simply execute the command with its parameters without having to separate them? Thank you in advance for your answers :)
-
nope, the point should be to learn using fork(). The exercise asks to execute n bash commands at the same time. But my professor said that system() causes a lot of security issues so we should learn to avoid it... Anyway, if I don't find anything else I have no problem doing the string parse...I just wanted to find a more "elegant" solution :Duser3523375– user35233752014-04-11 11:04:56 +00:00Commented Apr 11, 2014 at 11:04
Add a comment
|
2 Answers
This is a way to execute a command without parsing the command and its various parameters:
execl("/bin/sh", "/bin/sh", "-c", "your-command-without-parsing", 0);
2 Comments
user3523375
man, that's perfect! Works like a charm...by the way, how does it work? I can't understand why you passed "/bin/sh" as the second argument. Also, shouldn't the last argument be a zero?
You are right, the last argument must be a zero. As for the second arg, you can take a look at the description of execl: linux.die.net/man/3/execl. Or take a look at stackoverflow.com/questions/12596839/…
First of all, that's not a "bash" command. bash is a shell, but what you have there is a program command line.
You should look into the syscalls
- fork – used to create a new process
- execve – used to replace the process image with the program from a different binary.
- waitpid – used to wait for termination of the forked process
To give you a head start, here's how you launch a shell from your program without invoking system(…):
pid_t spawnshell(void)
{
char *argv[]={"/bin/sh", 0};
char *envp[]={0};
pid_t shpid = fork();
if(!shpid) {
execve(argv[0], argv, envp);
perror("execve");
assert(0 && "execve failed");
_exit(-1);
}
return shpid;
}
2 Comments
datenwolf
@ErikAigner: somewhere else. The purpose of the function above is to start a shell as a process, not wait for it to exit.