FBB::SharedStream(3bobcat)

πŸ“¦
version 6.07.01 Β· 5 versions
, in debian trixie, ubuntu questing

πŸ’– FBB::SharedStream β€” I/O on shared memory πŸ’–

okay bestie, welcome to the bobcat manual, section 3 πŸŽ€ this whole page is about a little class called FBB::SharedStream, and it's literally giving "iostream but the file lives in shared memory" energy. no cap.


✨ NAME ✨

FBB::SharedStream β€” I/O operations on shared memory 🫢


🌸 SYNOPSIS 🌸

#include <bobcat/sharedstream>
Linking option: -lpthread -lbobcat

yes bestie, you link both of those, don't skip -lpthread, iykyk πŸ’…


πŸ¦‹ DESCRIPTION πŸ¦‹

This class is the ultimate mashup: it combines the features of the std::istream and std::ostream classes, and it operates on shared memory. And just like with std::fstream objects, you need a seekp or seekg member call to switch from writing to reading, or the other way around. it's giving "one lane road, no overtaking" 😭

Also, same as with std::fstream objects, FBB::SharedStream objects do not keep separate offsets for reading and writing. The seek-members always refer to the (single) offset maintained by the FBB::SharedMemory object that the SharedStream object interfaces to. one offset to rule them all πŸ‘‘

So even though tellg and tellp return identical values, you should not call tellg after writing to a SharedStream object, and you should not call tellp after reading from one. Because calling reading-related members (tellg) after writing and vice versa puts the stream in its fail state. bestie this is not a vibe, please respect the rule πŸ™ˆ


🌈 NAMESPACE 🌈

FBB

Every single constructor, member, operator and manipulator mentioned in this man-page lives in the namespace FBB. periodt.


⭐ INHERITS FROM ⭐

  • FBB::SharedBuf (private inheritance),
  • std::istream,
  • std::ostream,
  • FBB::SharedEnum__ (cf. sharedmemory(3bobcat) for a description of this base class).

look at all those ancestors, main character energy fr fr πŸ’…


πŸŽ€ SIZEUNIT ENUMERATION πŸŽ€

The enum SizeUnit defines these symbolic constants:

  • kB, representing 1024 (2**10) bytes of memory;
  • MB, representing 1048576 (2**20 bytes of memory;
  • GB, representing 1073741824 (2**30) bytes of memory )
ngl the original page is a little unhinged with those parentheses and I'm keeping them exactly as they are, because the facts do not change πŸ’€

πŸ’œ CONSTRUCTORS πŸ’œ

  • SharedStream() β€” The default constructor defines a stub SharedStream object that cannot immediately be used to access shared memory. To use it, its member open must first be called. it's giving "placeholder bestie, come back later" πŸ¦‹
  • SharedStream(size_t maxSize, SizeUnit sizeUnit, std::ios::openmode openMode = std::ios::in | std::ios::out, size_t access = 0600) β€” This constructor creates a stream inheriting the facilities of an std::istream and std::ostream that interfaces to a shared memory segment having a capacity of at least maxSize * sizeUnit bytes. 🌸

By default, the shared memory segment is opened for reading and writing. Different from the open modes used for file streams, creating a shared memory stream with open modes ios::in | ios::out is OK. In this case the shared memory segment is created and once information has been written to the shared memory it can also be read again. so yes, you can have both, slay ✨

The shared memory's access rights are defined by the access parameter, interpreted as an octal value, using the well-known (chmod(1)) way to define the access rights for owner, group and others.

If construction fails, an FBB::Exception is thrown. 😭

  • SharedStream(int id, std::ios::openmode openMode = std::ios::in | std::ios::out) β€” This constructor creates a stream inheriting the facilities of an std::istream and std::ostream that connects to a shared memory segment having ID id.

Specifying the ios::trunc flag immediately clears the content of the shared memory. 🧹

An FBB::Exception is thrown if construction fails (e.g., no shared memory segment having ID id exists),

Copy and move constructors (and assignment operators) are not available. not me trying to copy it, nope, blocked πŸ’€


🌟 MEMBER FUNCTIONS 🌟

All members of std::istream and std::ostream and the enum values kB, MB, and GB, defined by FBB::SharedEnum__ are available. yes bestie, you get the whole inheritance package 🎁

  • FBB::SharedCondition attachSharedCondition(std::ios::off_type offset, std::ios::seekdir origin) β€” Returns an FBB::SharedCondition(3) object, interfacing to a shared condition variable located at offset offset (relative to origin) in the SharedMemory object to which the SharedStream object interfaces. This member does not alter the value returned by the stream's tellg and tellp members. πŸ™…β™€οΈ

An FBB::Exception is thrown if the FBB::SharedCondition object could not be constructed. 😭

  • FBB::SharedCondition createSharedCondition() β€” Returns an FBB::SharedCondition(3) object, interfacing to a newly created shared condition variable which is created at the current offset of the SharedMemory object to which the SharedStream object interfaces (or at the first offset of the next physical shared memory data block, cf. sharedcondition(3bobcat)). Creating a SharedCondition object does not alter the value returned by the stream's tellg and tellp members. πŸ’–

An FBB::Exception is thrown if the FBB::SharedCondition object could not be constructed. 😭

  • int id() const β€” The ID of the shared memory segment is returned. πŸͺͺ
  • void kill() β€” Without locking the shared memory first, all shared memory is returned to the operating system. The FBB::SharedStream object is unusable after returning from kill. Other processes that were using the shared memory can continue to do so. πŸ‘‘
bestie this one does NOT lock first, that's literally in the description, so be careful with it πŸ”₯
  • void memInfo(std::ostream &out, char const *end = "\n") β€” Information about the SharedMemory object is inserted into the provided ostream object. The IDs of the shared segments, their sizes, the maximum number of shared memory segments, the number of bytes that can be read from the shared memory, and its actual storage capacity, etc., are displayed. Following the information about the shared memory, end is inserted into out. πŸ“Š
  • void open(size_t maxSize, SizeUnit sizeUnit, std::ios::openmode openMode = std::ios::in | std::ios::out, size_t access = 0600) β€” This member creates a shared memory segment having a capacity of at least maxSize * sizeUnit bytes, and connects the shared memory segment to the FBB::SharedStream. A matching close member does not exist and is not required. πŸŽ€

By default, the shared memory segment is opened for reading and writing. Different from the open modes used for file streams, creating a shared memory stream with open modes ios::in | ios::out is OK. In this case the shared memory segment is created and once information has been written to the shared memory it can also be read again. ✨

The shared memory's access rights are defined by the access parameter, interpreted as an octal value, using the well-known (chmod(1)) way to define the access rights for owner, group and others.

If opening fails, an FBB::Exception is thrown. 😭

  • void open(int id, std::ios::openmode openMode = std::ios::in | std::ios::out) β€” This member connects the FBB::SharedStream object to a shared memory segment having ID id. A matching close member does not exist and is not required. If opening succeeds the shared memory is ready for use. 🫢

Specifying the ios::trunc flag immediately clears the content of the shared memory. 🧹

An FBB::Exception is thrown if opening fails (e.g., no shared memory segment having ID id exists). 😭

  • void remove() β€” The shared memory is first locked. Next, all shared memory is returned to the operating system. The FBB::SharedStream object is unusable after returning from remove. Other processes that were using the shared memory can continue to do so. πŸ‘‘
see how this one locks first and kill doesn't? yeah. that's the whole difference, don't mix them up πŸ’…
  • bool truncate(std::streamsize offset) β€” If offset is not exceeding the value returned by seekg(0, std::ios::end), then this latter value is changed to offset and true is returned. Otherwise false is returned, and the value returned by seekg is not altered. If the value returned by tellg exceeded offset, tellg's return value it is reduced to offset as well. Subsequent read operations on the shared memory can only succeed as long as tellg's return value hasn't reached the value offset. βœ‚οΈ

okay that's part 1 bestie, hold on, there's more coming πŸ’–

πŸŽ€ EXAMPLE πŸŽ€

okay bestie, THIS is the example program, and it is highkey a whole interactive playground for shared segments πŸ’– it's giving "type a letter, get a segment" energy. here it is, exactly as it lives in the source:

#include <iostream>
#include <string>
#include <ostream>
#include <istream>

#include <bobcat/exception>
#include <bobcat/sharedstream>
#include <bobcat/sharedcondition>

using namespace std;
using namespace FBB;

int main()
{
    SharedStream sharedStream;

    int id = -1;

    while (true)
    {
        cout <<
                "\n"
                " K             kill (no lock) existing shared segment\n"
                " S             show stats of current shared segment\n"
                " L <id>        Load segment <id>\n"
                " C             Install a SharedCondition at offset 0\n"
                " c            create new shared memory (sets id)\n"
//                " l            lock segment id until key pressed\n"
//                " p <x> c      put char c at offset x\n"
                " q            quit\n"
//                " r <x> <n>    read n chars from offset x\n"
//                " w <x> args   write all args at offset x\n"
                  " i            insert lines (until empty) at the current "
                                                                "offset\n"

                  " x            extract lines (until EOF) from the current "
                                                                "offset\n"
                  " X            extract the next line from the current "
                                                                "offset\n"
                  "              when nodified via ’N’\n"
                  " N            notify a waiting X\n"
                  " s <x>        seek (abs) offset x\n"
                "? ";

        char ch;
        cin >> ch;

        ios::off_type offset;

        cout << "Requested: " << ch << ’\n’;

        sharedStream.clear();

        switch (ch)
        {
            case ’c’:
            {
                sharedStream.open(1, SharedStream::kB);

                id = sharedStream.id();
                cout << "id = " << id << ’\n’;
                sharedStream.memInfo(cout);
                cout << ’\n’;
            }
            break;

            case ’C’:
            {
                sharedStream.seekp(0);
                SharedCondition cond(sharedStream.createSharedCondition());
                sharedStream.seekg(cond.width());
                break;
            }

            case ’K’:         // delete segment
            {
                if (id == -1)
                {
                    cout << "No segment loaded\n";
                    continue;
                }

                cout << "Removing segment id = " << id << ’\n’;
                if (ch == ’R’)
                    sharedStream.remove();
                else
                    sharedStream.kill();

                id = -1;
            }
            break;

            case ’L’:
                cin >> id;
                cout << "Loading segment " << id << ’\n’;
                sharedStream.open(id);
                sharedStream.memInfo(cout);
                cout << ’\n’;
            break;

            case ’S’:
                if (id == -1)
                {
                    cout << "No segment loaded\n";
                    continue;
                }
                sharedStream.memInfo(cout);
                cout << ’\n’;
            break;

            case ’s’:
            {
                size_t offset;
                if (id == -1)
                {
                    cout << "No segment loaded\n";
                    continue;
                }
                cin >> offset;
                sharedStream.seekg(offset);
                sharedStream.seekp(offset);
                cout << "tellg: " << sharedStream.tellg() << ", "
                        "tellp: " << sharedStream.tellp() << ’\n’;
            }
            break;

            case ’i’:
            {
                string line;
                getline(cin, line);
                sharedStream.seekp(0, ios::cur);
                while (true)
                {
                    cout << "? ";
                    if (not getline(cin, line) || line.empty())
                        break;
                    sharedStream << line << endl;
                    cout <<
                            "   tellp: " << sharedStream.tellp() << ’\n’;
                }
                    cout << // "   tellg: " << sharedStream.tellg() << ", "
                            "   tellp: " << sharedStream.tellp() << ’\n’;
            }
            break;

            case ’x’:
            {
                string line;
                sharedStream.seekg(0, ios::cur);

                while (true)
                {
                    cout << ": ";
                    if (not getline(sharedStream, line))
                        break;
                    cout << line << "\n"
                            "   tellg: " << sharedStream.tellg() << ", "
                            "   tellp: " << sharedStream.tellp() << ’\n’;
                }
            }
            break;

            case ’X’:
            {
                SharedCondition cond(sharedStream.attachSharedCondition(0));

                string line;
                sharedStream.seekg(cond.width());

                cond.lock();

                while (true)
                {
                    cond.wait();

                    cout << ": ";
                    if (not getline(sharedStream, line))
                        break;

                    cout << line << "\n"
                            "   tellg: " << sharedStream.tellg() << ", "
                            "   tellp: " << sharedStream.tellp() << ’\n’;
                }
                cout << "All done\n";
                cond.unlock();
            }
            break;

            case ’N’:
            {
                string line;
                getline(cin, line);

                SharedCondition cond(sharedStream.attachSharedCondition(0));
                while (true)
                {
                    cout << "’enter’ or ’q’? ";
                    getline(cin, line);

                    if (line == "q")
                        break;

                    cond.lock();
                    cond.notify();
                    cond.unlock();
                }
            }
            break;

            case ’p’:           // put a char behind the last written
            {
                if (id == -1)
                {
                    cout << "No segment loaded\n";
                    continue;
                }

                cin >> offset >> ch;
                if (!cin)
                    throw Exception() << "cmd specification error";

                sharedStream.seekp(offset);
                cout << "Segment id = " << id << " at write offset " <<
                                                    sharedStream.tellp() << ’\n’;
                sharedStream.put(ch);
            }
            break;

            case ’r’:           // put a char behind the last written
            {
                if (id == -1)
                {
                    cout << "No segment loaded\n";
                    continue;
                }

                int n;

                cin >> offset >> n;
                if (!cin)
                    throw Exception() << "cmd specification error";

                char buf[n];

                sharedStream.seekg(offset);
                cout << "Segment id = " << id << " at offset " <<
                         sharedStream.tellg() << ", to read " << n << " bytes\n";

                n = sharedStream.read(buf, n).gcount();

                if (n < 0)
                    cout << "No data at " << offset << ’\n’;
                else
                {
                    cout << "Retrieved " << n << " bytes, containing `";
                    cout.write(buf, n);
                    cout << "’\n";

                    for (auto ch: buf)
                        cout << static_cast<int>(ch) << ’ ’;
                    cout << ’\n’;
                }
            }
            break;

            case ’w’:           // write chars at offset
            {
                if (id == -1)
                {
                    cout << "No segment loaded\n";
                    continue;
                }

                string line;

                cin >> offset;
                getline(cin, line);
                if (!cin)
                    throw Exception() << "cmd specification error";

                streampos pos = sharedStream.seekp(offset).tellp();

                cout << "Segment id = " << id << " at offset " <<
                         pos << ", to write " << line.length() << " bytes\n";

                sharedStream.write(line.data(), line.length());

                if (!sharedStream)
                    cout << "No room left to write any bytes\n";
                else
                    cout << "Wrote " << (sharedStream.tellp() - pos) << " bytes\n";
            }
            break;

            case ’q’:
            return 0;

            default:
                cout << "request not implemented: " << ch << ’\n’;
            break;
        }
    }
}

a few things you're gonna clock while you're poking around in there 🌸

  • the menu string only advertises K, S, L <id>, C, c, q, i, x, X, N, s <x> and ? β€” the other keys (l, p <x> c, r <x> <n>, w <x> args) are sitting right there in the source but commented out of the menu.
  • and yet case ’p’:, case ’r’: and case ’w’: are very much alive down at the bottom of the switch, so they'll still fire if you type them πŸ‘€
  • case ’X’: and case ’N’: are the duo that talk to each other through a SharedCondition β€” one waits, the other lock()s, notify()s and unlock()s πŸ””
  • case ’q’: is your escape hatch β€” it just return 0;s and you're out the door πŸƒβ€β™€οΈ
  • not me noticing that case ’p’: and case ’r’: carry the exact same comment (// put a char behind the last written) even though ’r’ is reading, not putting πŸ™ˆ
πŸ’… it's giving "demo program that doubles as a stress test", and honestly? slay.

πŸ“ FILES πŸ“

  • bobcat/sharedstream β€” defines the class interface

πŸ‘€ SEE ALSO πŸ‘€


πŸ’€ BUGS πŸ’€

ok bestie, this one's important, do not skip it 🚨

by default, exceptions thrown from inside a std::stream object get caught by the stream object itself, and that just quietly sets its ios::failbit flag. sneaky little guy.

if you want exceptions to actually leave a stream object, you call its exceptions member, like this:

myStream.exceptions(ios::failbit | ios::badbit | ios::eofbit);

that's the move. πŸ”“βœ¨

...and bestie, if you wanna go straight to the source, here's where the Bobcat lore lives πŸ’…

And the Debian Bobcat project files situation:

  • libbobcat6: the debian package holding the shared library, the changelog and the copyright note, iconic;
  • libbobcat-dev: the debian package with the static library, the headers, the manual pages, and all the developer info. literally everything you need 🫢

🌈 BOBCAT

Okay so fun fact, Bobcat is an acronym of Brokken’s Own Base Classes And Templates. Not me thinking it was just a cute lil wildcat this whole time 😭 no cap, that's the actual name, periodt.


This is free software, distributed under the terms of the GNU General Public License (GPL). Free as in freedom bestie, slay πŸŽ€


πŸ‘‘ AUTHOR

Frank B. Brokken (f.b.brokken@rug.nl). The literal father of Bobcat, we stan πŸ’œ


And that's a wrap on this one, bestie!! πŸ¦‹βœ¨ This whole thing shipped as part of libbobcat-dev, version 6.07.01, dated 2005-2025 β€” yeah, twenty whole years of Bobcat, that's longevity, that's legacy, that's ate and left no crumbs πŸ”₯πŸ‘‘ Go forth and stream your shared objects responsibly, ily, bye!! πŸ’–πŸŒΈ

πŸ“¦ where this page comes from