1

the code snippet I wrote is like this:

#include <stdlib.h>

int main()
{
  system("/bin/bash ls");
}

when I compile and execute the binary, I got the result: /bin/ls: /bin/ls: cannot execute binary file

so what's the thing missing here?

1
  • Have you tried without the path? system("ls"); Commented Dec 3, 2012 at 18:06

3 Answers 3

5

ls is an actual system binary. it's not a built-in shell command. All you need is system("ls"). Right now you're trying to pass the contents of the ls binary file into bash as a script.

Sign up to request clarification or add additional context in comments.

4 Comments

@sidyll: uh, why? echo 'Hi' and echo "Hi" are functionally identical. There's no variables in the command, so...?
ah man... this is what I get for 2 hours sleep. sorry, you're right.
No problems ;-) We can delete these comments if you want
@Marc: if the command I need execute via system is like "/bin/bash unknown", then how can I know the unknown is a binary or a bash buit-in? maybe I can execute which to test the unknown, but are there better ways?
3

Do not use system() from a program , because strange values for some environment variables might be used to subvert system integrity. Use the exec(3) family of functions instead, but not execlp(3) or execvp(3). system() will not, in fact, work properly from programs with set-user-ID or set-group-ID privileges on systems on which /bin/sh is bash version 2, since bash 2 drops privileges on startup. (Debian uses a modified bash which does not do this when invoked as sh.)

In your case , ls is not built in command in shell so system() is not working.

You can check using type <cmd_name> command to know that cmd_name is built-in or not.

For more man system()

Comments

2

If no options are specified, the argument to /bin/bash is the name of a file containing shell commands to execute.

To execute commands specified on the command line, use the -c option: /bin/bash -c ls.

As others have noted, there are security considerations when doing this, so you should seek alternatives.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.