1
$\begingroup$

Here's a snippet of C++ code:

#include <stdint.h>
#include <time.h>
#include <iostream>
#include <unistd.h>

#include <wstp.h>

using namespace std;

WSEnvironment env_h;

int main() {
    pid_t server_pid;
    int err;

    env_h = WSInitialize(0);

    server_pid = getpid();
    bool done = false;
    fork();
    if (server_pid == getpid()) {
        auto server_h = WSNewLinkServerWithPortAndInterface(env_h, 17700, "127.0.0.1", nullptr, &err);
        if (err) {
            cout << "WSTP error " << err << " on server process" << endl;
            return err;
        }
        int64_t data = 0;
        cout << "[Server] waiting for new link" << endl;
        auto server_link_h = WSWaitForNewLinkFromLinkServer(server_h, &err);
        if (err) {
            cout << "WSTP error " << err << " on server process" << endl;
            return err;
        }
        cout << "[Server] activating new link" << endl;
        WSActivate(server_link_h);
        cout << "[Server] getting data from link" << endl;
        WSGetInteger64(server_link_h, &data);
        cout << "[Server] got data: " << data << endl;
        WSClose(server_link_h);
    } else {
        cout << "[Client] creating new link" << endl;
        auto client_link_h = WSOpenString(env_h, "-linkconnect -linkname [email protected] -linkprotocol TCPIP -linkoptions 4", &err);
        if (err) {
            cout << "WSTP error " << err << " on server process" << endl;
            return err;
        }
        cout << "[Client] activating new link" << endl;
        WSActivate(client_link_h);
        cout << "[Client] sending data" << endl;
        WSPutInteger64(client_link_h, 12345);
        WSEndPacket(client_link_h);
        WSFlush(client_link_h);
        sleep(1);
        WSClose(client_link_h);
        cout << "[Client] closed link" << endl;
    }
    WSDeinitialize(env_h);
    return 0;
}

It works, but WSWaitForNewLinkFromLinkServer appears to be blocked for a few seconds before any request could be processed.If I send multiple requests to the server, then each request will get its own delay. I'm sure not what's the underlying problem.

My system is Ubuntu 18.04 with M11.3. The above code is compiled via:

WSTP_PATH=/usr/local/Wolfram/Mathematica/11.3/SystemFiles/Links/WSTP/DeveloperKit/Linux-x86-64/CompilerAdditions
g++ a.cpp -I$WSTP_PATH -L$WSTP_PATH -lWSTP64i4 -luuid -lrt -ldl

Run it with:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$WSTP_PATH
./a.out

PS: for anyone wondering what -linkoptions 4 does, check here.

$\endgroup$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.