在命名管道中获取分段错误(核心转储)错误

问题描述 投票:-1回答:1

尝试在Ubuntu上使用C ++和python中的命名管道实现反向字符串,当我尝试接受用户输入时出现Segmentation Fault(Core Dumped)错误。当字符串被预定义时,程序可以完美地工作。

以下是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

谷歌搜索后,我发现这意味着尝试访问内存的只读部分。

但是,如何从用户处获取字符串时如何删除此错误?我是否需要更改文件权限,以便在阅读时写入?什么可能有用?

python c++ segmentation-fault named-pipes coredump
1个回答
1
投票

This记录了您目前正在使用的operator>>超载:

template<class CharT, class Traits>
basic_istream<CharT,Traits>& operator>>(basic_istream<CharT,Traits>& st, CharT* s);

这实际上意味着粗略

basic_istream<char>& operator>>(basic_istream<char>& st, char* s);

(你用st = cins = msg称呼它)。

文档说这个重载

...提取连续的字符并将它们存储在第一个元素由s指向的字符数组的连续位置

s(或msg)并未指向可存储这些字符的数组。它是未初始化的,并且存储任何内容而不将其初始化为指向某个有效位置的是Undefined Behavior。

无论如何都不建议使用此过载,因为您无法安全使用它。您事先不知道将读取多少字节,这意味着您无法为阵列选择安全大小来存储它们。

使用std::string overload代替允许字符串类来处理存储,但是读取了许多字节,因为std::string(与普通数组不同)可以根据需要自行增长。

© www.soinside.com 2019 - 2024. All rights reserved.