本文介绍了在后台执行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个模仿真实bash shell的minishell.我在后台执行诸如ls &之类的命令.

I am implementing a minishell that will emulate a real bash shell. I am stacked with the execution of commands in background such as ls &.

我的第一种方法是以下方法(无效)

My first approach was the following (which does not work)

char *execArgs[] = { "ls", "&", NULL };
execvp("ls", execArgs);

然后,我尝试了另一种方法,即修改了fork()的父进程,而不是等待子进程以防它在后台运行.这里的问题是,然后它应该打印在后台运行的作业列表,以便在bash shell中模拟后台行为,但是命令jobs不能作为execvp()的参数正确执行.

Then, I tried another way by modifying the parent process of the fork() and not waiting for the child in case it should be run in background. The problem here is that then it should print the list of jobs running on background in order to simulate the background bahaviour in a bash shell, but the command jobs is not executed correctly as a parameter of execvp().

我的问题是,有没有更简单的方法可以在C中实现此后台调用?如果没有,在我提到的任何一个选项中会失败吗?

My question is, is there any easier way to implement this background calls in C? In case there isn't, what does it fail in either of the options that I have mentioned?

推荐答案

示例失败的原因是

  • &"如您所编码,它是"ls"程序的一个参数.当您在shell提示符下输入命令时,&"被shell占用,"ls"程序再也看不到背景了.
  • "exec()"调用终止当前程序(即您的迷你外壳).

您可能想要的是

system("ls &");

读一本不错的Unix书.您将需要了解fork(),exec(),wait()等.

Read a good Unix book. You will need to know fork(), exec(), wait() and more.

这篇关于在后台执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 17:43
查看更多