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 :)
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);
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With