【发布时间】:2019-10-31 00:52:14
【问题描述】:
我正在为我的 UNIX 和网络编程课程做家庭作业,我必须重写 UNIX 管道 (|) 功能。
我尝试了多种方法,例如更改部分代码无济于事,并使用 GDB 尝试调试代码,但它并没有指向任何地方。我已经做了一些错误检查,包括在用户输入空值时退出程序(循环),但这似乎没有帮助。
// Variable declarations.
char command1[255], command2[255];
char *tok1, *tok2;
string file_path;
int pipefd[2], rs;
// Loop indefinitely.
while(1) {
// Get user input and store it.
// command 1
cout << "command1? ";
cin.getline(command1, 255);
// tokenize the command based on space as the delimiter
tok1 = strtok(command1, " ");
// if user typed quit, stop the loop.
if((string)tok1 == "quit") break;
// if user left field blank, error and stop the loop.
if(tok1==NULL) { cerr << "pipe: Must enter a command.\n"; break; }
// command 2
cout << "command2? ";
cin.getline(command1, 255);
// tokenize the command based on space as the delimiter
tok2 = strtok(command2, " ");
// if user typed quit, stop the loop.
if((string)tok2=="quit") break;
// if user left field blank, error and stop the loop.
if(tok2==NULL) { cerr << "pipe: Must enter a command.\n"; break; }
}
...循环在管道和叉子之后结束,所有这些都完成了,缩短到我认为问题所在的地方。
以下错误不断出现,我不知道如何修复它。
command1? ls
command2?厕所
在抛出 'std::logic_error' 实例后调用终止
what(): basic_string::_M_construct null 无效
【问题讨论】:
-
看起来程序试图从空指针构建
std::string。strtok用完令牌或检测到错误时返回 NULL。 -
那么这是否意味着 command1/command2 在某些时候为空?如果我输入命令,我不确定如何或为什么会发生这种情况。
-
您的第二个
getline在应该读入command2时读入 command2。 -
嘿,我能说服你用
std::getline读入std::string,然后用std::istringstream解析吗?类似getline(cin, command1); istringstream strm(command1); strm >> tok1; -
哦,嘿,如果您使用的是 gdb,这里有一个针对 C++ 异常的 gdb 调试技巧。在 gdb 提示符处运行程序之前,请写入
catch throw,这就像抛出异常的断点一样。我相信你也可以做到catch catch。