我正在学习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;
}
Run Code Online (Sandbox Code Playgroud)
我实际运行程序时的输出是:
$ ./a.out
shell>> ls -l
0: ls
1: -l
done tokenizing...
0: ls
1: -l
done tokenizing...
Run Code Online (Sandbox Code Playgroud)
我不确定为什么会这样做.任何人都可以指导我正确的方向吗?谢谢
该fork函数返回两次,一次在原始进程中,一次在新创建的分叉进程中.然后这两个进程都会调用tok.
你打电话似乎没有任何明确的理由fork.所以修复可能就像消除调用一样简单fork.