gpt4 book ai didi

c++ - 奇怪的异常抛出 - 分配 : Operation not permitted

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:04:32 25 4
gpt4 key购买 nike

我想从 cin 进行异步读取,因此我有一段代码

客户端.h

...
boost::asio::posix::stream_descriptor input;
boost::asio::streambuf input_buffer

客户端.cpp

Client::Client(int argc, char **argv, boost::asio::io_service &io_service)
: tcp_socket(io_service)
, udp_socket(io_service)
, input(io_service, ::dup(STDIN_FILENO))
{
...
read_std_input();
}

void Client::read_std_input() {
async_read_until(input, input_buffer, '\n',
boost::bind(&Client::handle_std_read, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}

问题是:当我以正常方式 [ ./client ] 运行我的客户端,然后通过命令之类的方式输入内容时,它就像魅力一样工作。但是,当我通过 [ ./client < test ] 运行它时,它会抛出:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl

' what(): assign: Operation not permitted Aborted

您知道问题可能出在哪里吗?谢谢!

最佳答案

Boost.Asio 的 POSIX 面向流的描述符明确不支持常规文件。因此,如果 test是一个普通文件,那么./client < test将导致 posix::stream_descriptor::assign() 尝试分配 STDIN_FILENO 时失败到 stream_descriptor . documentation状态:

Boost.Asio includes classes added to permit synchronous and asynchronous read and write operations to be performed on POSIX file descriptors, such as pipes, standard input and output, and various devices (but not regular files).

考虑传递 test 的内容归档到client通过管道。

$ cat test | ./client

这是一个完整的示例程序和演示:

#include <iostream>
#include <boost/asio.hpp>

void handle_read(
const boost::system::error_code& error,
std::size_t bytes_transferred
)
{
std::cout << "read " << bytes_transferred << " bytes with "
<< error.message() << std::endl;
}

int main()
{
boost::asio::io_service io_service;
boost::asio::posix::stream_descriptor input(io_service);

// Assign STDIN_FILENO to the stream_descriptor. It will support
// pipes, standard input and output, and various devices, but NOT
// regular files.
boost::system::error_code error;
input.assign(STDIN_FILENO, error);
if (error)
{
std::cerr << error.message() << std::endl;
return -1;
}

boost::asio::streambuf input_buffer;
async_read_until(input, input_buffer, '\n', &handle_read);
io_service.run();
}

演示

$ ./clienttesting standard inputenterread 23 bytes with Success$ echo "this is a test" > test$ ./client < testOperation not permitted$ cat test | ./clientread 15 bytes with Success

关于c++ - 奇怪的异常抛出 - 分配 : Operation not permitted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23614370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com