【发布时间】:2018-09-03 10:23:11
【问题描述】:
尝试在 Ubuntu 上使用 C++ 和 python 中的命名管道实现反向字符串,当我尝试接受用户输入时出现分段错误(核心转储)错误。预定义字符串时,程序可以完美运行。
以下是写入文件的 C++ 编写程序:
#include <fcntl.h>
#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <string.h>
using namespace std;
int main()
{
int fd;
char *myfifo = "/home/Desktop/myFile";
/* create the FIFO (named pipe) */
mkfifo(myfifo, 0666);
/* write message to the FIFO */
fd = open(myfifo, O_WRONLY);
char const*msg;
cout << "Please enter string to be reversed: ";
cin>>msg;
// msg="This is the string to be reversed";
// The above line works fine which is pre-defined string.
write(fd, msg, strlen(msg)+1);
close(fd);
/* remove the FIFO */
unlink(myfifo);
return 0;
}
以下是我的 Python Reader 程序:
import os
import sys
path= "/home/Desktop/myFile"
fifo=open(path,'r')
str=fifo.read()
revstr=str[::-1]
print(revstr)
fifo.close()
同时执行上述文件后,我分别得到以下输出:
Writer.cpp =>
Please enter string to be reversed: qwerty
Segmentation fault (core dumped)
Reader.py => No Output, Blank
谷歌搜索后,我发现这意味着尝试访问内存的只读部分。
但是,如何删除此错误以从用户那里获取字符串?我是否需要更改文件权限以使其在读取时写入?什么可能有效?
【问题讨论】:
-
msg没有与之关联的内存。使用std::string过轻松的生活? -
你有一个指针
msg,但你从来没有让它指向任何地方。 -
为了将来参考,您的输出显示生成了一个核心文件。学习在调试器中加载这些内容并亲自查看发生了什么是一项非常宝贵的实践技能(诚然,在这种情况下,basic_istream 模板可能会产生很多噪音,但值得一看)。
标签: python c++ segmentation-fault named-pipes coredump