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 :)
Asked
Active
Viewed 5,268 times
3
-
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 :D – user3523375 Apr 11 '14 at 11:04
2 Answers
5
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;
}

datenwolf
- 159,371
- 13
- 185
- 298
-
-
@ErikAigner: somewhere else. The purpose of the function above is to start a shell as a process, not wait for it to exit. – datenwolf Apr 28 '19 at 11:10
5
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);
-
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? – user3523375 Apr 11 '14 at 13:51
-
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: http://linux.die.net/man/3/execl. Or take a look at http://stackoverflow.com/questions/12596839/how-to-call-execl-in-c-with-the-proper-arguments – Apr 11 '14 at 14:53