C++函数运行两次但只调用一次

标签 c++ shell unix

我正在学习 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/

相关文章:

c++ - 在 C++ 中的类中定义 vector 的大小

linux - 在 Linux shell 中的文件夹中压缩文件夹

linux - find -exec 无法识别参数

unix - 如何通过键入脚本名称而不是 sh [scriptname] 来运行 shell 脚本?

c++ - 如何初始化一个点数组?

c++ - 如果大括号闭合列表的类构造函数大小错误,则编译时错误

c++ - 将数组的所有元素初始化为相同的数字

c - 如何在 shell 命令行中输入退格字符?

java - 使用 Jsch 和 Java 将 System.out 复制到文件

用于在特定搜索字符串模式之前和之后提取行的 Unix 命令