我正在学习 C++ [Java 背景 fwiw] 并尝试将 UNIX shell 编写为一个项目。我在标记执行输入时遇到了一个有趣的小问题。 tok 函数被调用了两次,我不确定为什么。我当前的测试代码如下:
#include <iostream>
#include <vector>
#include <sstream>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
using namespace std;
void tok(string, char**);
int main(){
const char* EXIT = "exit";
string input;
cout << "shell>> ";
getline(cin, input);
pid_t pid = fork();
char* args[64]; //arbitrary size, 64 possible whitespace-delimited tokens in command
tok(input, args);
return 0;
}
//copied from http://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c
void tok(string inStr, char** args){
int last = 0, next = 0, i = 0;
while( (next = inStr.find(' ', last)) != -1){
cout << i++ << ": " << inStr.substr(last, next-last) << endl;
*args++ = strdup(inStr.substr(last, next-last).c_str());
last = next + 1;
}
cout << i++ << ": " << inStr.substr(last) << endl;
*args++ = strdup(inStr.substr(last).c_str());
*args = '\0';
cout << "done tokenizing..." << endl;
}
我实际运行程序时的输出是:
$ ./a.out
shell>> ls -l
0: ls
1: -l
done tokenizing...
0: ls
1: -l
done tokenizing...
我不确定它为什么会那样做。谁能指导我正确的方向?谢谢
最佳答案
fork
函数返回两次,一次在原始进程中,一次在新创建的分支进程中。这两个进程随后调用 tok
。
您调用 fork
似乎没有任何明确的原因。因此,修复可能就像消除对 fork
的调用一样简单。
关于C++函数运行两次但只调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39212988/