所以我在写一个UNIX shell一类矿,基本上我参加一个参数,如果该参数具有“&”在它的结束,然后我需要的父进程调用等待();。有问题与派生进程
我在这里的问题是,该方案应接受输入,直到我键入exit,所以一切都在一个“而”循环。事情办得完美,直到我在它的结束通话与“&”命令,然后我可以看到,父进程结束,那么孩子结束,但我不是在我的正常提示接受的输入是“osh>”。
所以基本上这里是我的正常输出,当我运行一个简单的命令:
osh> ls -l
child:0
a.out main main.cpp main.cpp~
parent: 8695
但是当我在最后运行带有“&”命令出现这种情况:
osh> ls -l &
parent: 27082
osh> child:0
total 44
-rwxr-xr-x 1 myuser users 10368 Mar 1 14:46 a.out
-rwxr-xr-x 1 myuser users 23368 Mar 1 14:00 main
-rw-r--r-- 1 myuser users 1658 Mar 1 14:46 main.cpp
-rw-r--r-- 1 myuser users 1676 Mar 1 14:45 main.cpp~
<cursor is here accepting commands, but no osh> prompt>
如果任何人有任何意见或建议,将不胜感激。我觉得这只是一个小错误,但我已经多次运行调试器,找不到任何东西。我只是没有那么多的经验。下面是完整的代码来看看:
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <string.h>
#include <string>
#include <cstring>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#define MAX_LINE 80 //the maximum length command
using namespace std;
int main()
{
char* args[MAX_LINE/2 + 1]; //command line arguments
char str[41]; //intitialize string for input
int should_run = 1; //flag to determine when to exit program
bool status; //status of whether or not an ampersand is in the passed argument
while (should_run) {
int index = 0;
cout << "osh> ";
fflush(stdout);
cin.getline(str, 41);
args[index] = strtok(str, " ");
while (args[index] != NULL) {
index++;
args[index] = strtok(NULL, " ");
}
if (strcmp (args[0], "exit") == 0) //in input is "exit", exit the while loop
break;
if (*args[index - 1] == '&') //check whether to run processes concurrently
status = true;
args[index - 1] = NULL; //remove & to make sure arguments are valid
// (1) fork a child process using fork()
pid_t pid = fork();
if (pid < 0) { //error handling
perror("Fork Failed.");
break;
}
// (2) the child process will invoke execvp()
if (pid == 0) {
//child process
cout << "child:" << pid << endl;
if (execvp (args[0], args) == -1) {
perror ("exec");
}
}
// (3) if command didn't included &, parent will invoke wait()
//parent process
if (pid > 0) {
// parent process
if (!status) {
wait(0);
}
cout << "parent: " << pid << endl;
}
}
return 0;
}
编辑:也刚刚意识到我的第二个输出我张贴,它表明“职业安全与卫生>”父进程后,第二次,不知道该如何形容这个错误。
这几乎是如何在每个其他的Unix shell中工作。 – immibis
任何不使用C编写它的原因,它几乎都是? –
@NeilButterworth对C++ – HOAX