Haiyuan Zhang
Haiyuan Zhang

Reputation: 42792

can't execute bash command via c standard system function

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?

Upvotes: 1

Views: 2592

Answers (3)

Eric Postpischil
Eric Postpischil

Reputation: 222486

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.

Upvotes: 2

Omkant
Omkant

Reputation: 9204

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()

Upvotes: 3

Marc B
Marc B

Reputation: 360622

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.

Upvotes: 5

Related Questions