简体   繁体   English

执行与我的C程序不同的程序

[英]Executing a different program from my C program

I am writing a basic shell in Linux as a hobby, I want to start working on program execution, but have no idea on how to do this. 我正在业余爱好中用Linux编写基本的shell,我想开始进行程序执行,但是对如何执行此操作一无所知。 I have seen execp() and its various brothers and sisters, but apparently that forces the kernel to drop the currently running process, in this case my shell, and continue with the new process. 我已经看过execp()及其各种兄弟姐妹,但显然,这迫使内核放弃当前正在运行的进程(在本例中为我的shell),并继续执行新进程。

So basically all I need is a function that I can use to call a command such as ls or cd have it execute and then return to my shell. 因此,基本上我所需要的只是一个函数,可以用来调用lscd等命令使其执行然后返回我的shell。

All help is appreciated. 感谢所有帮助。

ouah's answer is essentially correct, but it won't work for cd . ouah的答案本质上是正确的,但不适用于cd Your shell needs to implement that as a builtin command (ie the shell needs to contain the code for cd . 您的外壳需要将其实现为内置命令(即外壳需要包含cd的代码)。

The reason for this is that fork first creates a new copy of the current process (the running instance of the shell, in this case). 这样做的原因是, fork首先创建了当前进程的新副本(在本例中为shell的运行实例)。 Then exec overwrites the new process with the executable you want to run. 然后exec用您要运行的可执行文件覆盖新进程。 When the command finishes, the new process terminates and goes away. 命令完成后,新进程终止并消失。 If you use this for cd it will change the working directory of the new process but leave the working directory of the old process (the shell) totally untouched. 如果将其用于cd ,它将更改新进程的工作目录,但完全不影响旧进程(shell)的工作目录。

使用fork创建一个新进程,然后调用exec

Use something like this: 使用这样的东西:

if (fork ()==0) {
    execl ("/bin/sh",NULL);
}

This will create the new process (an exact copy of already running one), then replace it with the new one. 这将创建新进程(已运行进程的精确副本),然后将其替换为新进程。 Please note this might require some workarounds in some environments where CPU does not fully support virtual memory, and your original process is so big that you can not duplicate it. 请注意,在某些CPU不完全支持虚拟内存的环境中,这可能需要一些解决方法,并且原始进程太大,无法复制它。

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

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