Uthman
Uthman

Reputation: 9807

Giving control to shell from a C code?

How can I execute shell from a C code?

My shell is placed in /bin/sh

Following didn't seem to work for me

system("/bin/sh");
exec("/bin/sh");

Upvotes: 0

Views: 186

Answers (2)

JeremyP
JeremyP

Reputation: 86651

This program works as expected for me:

int main()
{
    int ret = system("/bin/sh");
    printf ("Shell returned %d\n", ret);
    return 0;
}

using -i causes some sort of redirection issue and everything hangs as soon as I type a command that produces output.

There are important differences between system() and exec(). system() is effectively the same as /bin/sh -c yourCommand on the command line, so the system("/bin/sh") is the same as

/bin/sh -c /bin/sh

This is why it is rarely used, because the command you want is executed by first starting an unnecessary shell process.

exec() causes the entire process image to be replaced by the command specified so if I had written:

int main()
{
    int ret = exec("/bin/sh");
    printf ("Shell returned %d\n", ret);
    return 0;
}

The printf() and everything after it would never have been executed because the whole process transforms into an instance of /bin/sh. The proper way to run a child command is to fork and then exec in the child and wait in the parent.

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

Maybe you need to tell the shell it should be interactive:

system("/bin/sh -i");

However, I believe that your original system() call should have produced a shell prompt too.

Both notations (with and without the '-i') in this program give me a shell prompt (return to the previous shell by typing 'exit' and RETURN or Control-D):

#include <stdlib.h>
int main(void)
{
    system("/bin/sh -i");
    return 0;
}

Upvotes: 2

Related Questions