简体   繁体   English

通过C代码将控制权交给Shell?

[英]Giving control to shell from a C code?

How can I execute shell from a C code? 如何从C代码执行Shell?

My shell is placed in /bin/sh 我的外壳放在/bin/sh

Following didn't seem to work for me 关注似乎对我没有用

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

Maybe you need to tell the shell it should be interactive: 也许您需要告诉shell它应该是交互式的:

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

However, I believe that your original system() call should have produced a shell prompt too. 但是,我相信您原来的system()调用也应该产生了一个shell提示。

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 ): 该程序中的两种表示法(带和不带-i)都给我一个shell提示(通过键入'exit'和RETURNControl-D返回到先前的shell):

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

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. 使用-i会引起某种重定向问题,并且一旦键入产生输出的命令,一切都会挂起。

There are important differences between system() and exec() . system()exec()之间有重要区别。 system() is effectively the same as /bin/sh -c yourCommand on the command line, so the system("/bin/sh") is the same as system()实际上与命令行上的/bin/sh -c yourCommand相同,因此system("/bin/sh")

/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. 这就是为什么很少使用它的原因,因为所需的命令是通过首先启动不必要的Shell进程来执行的。

exec() causes the entire process image to be replaced by the command specified so if I had written: exec()导致整个过程映像被指定的命令替换,因此,如果我编写了:

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 . printf()及其之后的所有内容将永远不会执行,因为整个过程都将转换为/ bin / sh的实例。 The proper way to run a child command is to fork and then exec in the child and wait in the parent. 运行子命令的正确方法是先在子进程中派生然后执行,然后在父进程中等待。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM