I've tried to see if anyone else if having this problem, but I haven't found anything online yet. Does anything in this code looks like I'm invoking boost incorrectly?
This code works when I am logged into the machine that is starting the TCP server, but fails when no one is logged in. I stripped the code down to only look at the boost asio logic.
//create _acceptor, which will eventually listen for incomming connections, asynchronously
_acceptor = boost::shared_ptr<tcp::acceptor>(new tcp::acceptor(*_io_service));
_acceptor->open(tcp::endpoint(tcp::v4(), _port).protocol());
_acceptor->set_option(tcp::acceptor::reuse_address(false));
//omitted logic find a port that is open
_acceptor->bind(tcp::endpoint(tcp::v4(), _port));
//omitted error handling logic if open port not found
//Start listening for incoming connections asynchronously.
_acceptor->listen();
sslSocketPtr ssl_socket(sslSocketPtr(new ssl::stream<ip::tcp::socket>(*_io_service, _sslContext)));
_acceptor->async_accept(ssl_socket->lowest_layer(),
boost::bind(&TCPServer::handle_sslAccept, shared_from_this(), boost::asio::placeholders::error, ssl_socket));
When no one is logged into the machine, the ssl_socket constructor throws the exception: "static_mutex: Access is denied".
If I define BOOST_ASIO_ENABLE_OLD_SSL the code works correctly, but I think that may be contributing to another bug in my code. So I am trying to use the latest SSL logic from Boost.
Any help would be appreciated!
I'm going to assume from the symptoms that you run on Windows.
On windows, static_mutex is implemented as a named (interprocess) mutex and gets "opened" using CreateMutexW:
If the mutex is a named mutex and the object existed before this function call, the return value is a handle to the existing object, GetLastError returns ERROR_ALREADY_EXISTS, bInitialOwner is ignored, and the calling thread is not granted ownership. However, if the caller has limited access rights, the function will fail with ERROR_ACCESS_DENIED and the caller should use the OpenMutex function.
As you can see you don't have the required permissions. However, you could still have this working if the mutex is always created by a privileged process. In that case you could modify the code that opens an existing named mutex with OpenMutex as the documentation hints.
It's likely easier to run the process under a user that has the required permissions thought
Related
I am using boost::asio to implement network programming and running into timing issues. The issue is currently most with the client.
The protocol initially begins by the server returning a date time string to the user, and the client reads it. Up to that part it works fine. But What I also want is to be able to write commands to the server which then processes them. To accomplish this I use the io_service.post() function as shown below.
io_service.post(boost::bind()); // bounded function calls async_write() method.
For some reason the write tries happens before the initial client/server communication, when the socket has not been created yet. And I get bad socket descriptor error.
Now the io_service's run method is indeed called in another thread.
When I place a sleep(2) command before post method, it work fine.
Is there way to synchronize this, so that the socket is created before any posted calls are executed.
When creating the socket and establishing the connection using boost::asio, you can define a method to be called when these operations have either completed or failed. So, you should trigger your "posted call" in the success callback.
Relevant methods and classes are :
boost::asio::ip::tcp::resolver::async_resolve(...)
boost::asio::ip::tcp::socket::async_connect(...)
I think the links below
will give u some help
http://www.boost.org/doc/libs/1_42_0/doc/html/boost_asio/reference/io_service.html
My company is developing a hardware that needs to communicate with software. To do this, we have made a driver that enables writing to and reading from the hardware. To access the driver, we use the command:
HANDLE device = CreateFile(DEVICE_NAME,
GENERIC_READ | GENERIC_WRITE,
0x00000007,
&sec,
OPEN_EXISTING,
0,
NULL);
Reading and writing is done using the functions:
WriteFile(device,&package,package.datasize,&bytesWritten,NULL);
and
ReadFile(device,returndata,returndatasize,&bytesRead,NULL);
And finally, CloseHandle(device), to close the file.
This works just fine in the case where the functions are called from the main thread. If they are called from some other thread, we get error 998 (no_acccess) when trying to Write more than a couple of elements. The threads are created using
CreateThread(NULL, 0, thread_func, NULL, 0, &thread_id);
I'm running out of ideas here, any suggestions?
edit:
When running the following sequence:
Main_thread:
CreateFile
Write
Close
CreateThread
WaitForThread
Thread_B:
CreateFile
Write
Close
Main_Thread succeeds and Thread_B does not. However, when writing small sets of data, this works fine. May this be because Thread_B does not inherit all of Main_Thread's access privileges?
edit2:
a lot of good thinking going on here, much appreciated! After some work on this problem, the following seems to be the case:
The api contains a Queue-thread, handling all packages going to and from the device. This thread handles pointers to package-objects. When a pointer reaches the front of the queue, a "send_and_get" function is called. If the arrays in the package is allocated in the same thread that calls the "send_and_get" function, everything works fine. If the arrays are allocated in some other thread, sending fails. How to fix this, though, I don't know.
According to winerror, Win32 error 998 is one of the following native status values (which would be returned by the O/S or the driver):
998 ERROR_NOACCESS <--> 0x80000002 STATUS_DATATYPE_MISALIGNMENT
998 ERROR_NOACCESS <--> 0xc0000005 STATUS_ACCESS_VIOLATION
998 ERROR_NOACCESS <--> 0xc00002c5 STATUS_DATATYPE_MISALIGNMENT_ERROR
Access violation might be a likely candidate based on you saying, "when trying to Write more than a couple of elements." Are you sure the buffer that you're sending is large enough?
The alignment errors are fairly exotic, but might be relevant if the device has some alignment requirements and the developer chose to use these particular errors.
-scott
Still sounds to me like it's concurrent access.
Your separate threads writing to this device will need to properly protect access to the file using a mutex or similar. Either open the handle in the main thread and leave it open or protect the whole Open -> Write -> Close sequence that can occur in each thread (with a mutex).
As a debugging measure, since it's your own driver, you could get the driver to log the requests it is receiving, e.g., into the event log. Set up two test runs which are identical except that one runs all the code in the main thread and the other runs all the code in a second thread. Comparing the results should give you a better insight into what is happening.
It would also be a good idea to get your driver to report any error codes that it is returning to the operating system.
First thing that you should check is if the error (998) reported by your driver or by the kernel-mode I/O manager (which is responsible to initiate the IRP and call your driver) even before the request reaches your driver. You should be able to discover this since this is your driver. Just log the calls to the driver's Dispatch routine, what it returns, what it does (does it call other drivers or calls IoCompleteRequest with an error code or etc.) and things should become clear.
From the scenario that you describe it seems that most likely the error is caused by your driver. For instance, your driver may allocate some global state structure on a response to CreateFile (which is driver's IRP_MJ_CREATE), and purge it when the file is closed. Such a driver won't function correctly if simultaneously two files are opened, then one is closed whereas the second still receives I/O requests.
I made a MFC application which probably has two threads, one for receiving data from a socket using UDP protocol and one is the main thread of MFC app. While any data is received some objects, created in the main thread by new operator, would be notified to fetch the data through apply the observer design pattern. The problem is that sometimes after I clicked the close system button, the GUI of the app disappeared, but its process can still be found in the Task Manager. If I stop the data source (UDP client) this problem would never happen. Other important and maybe helpful information is listed below:
The Observer design pattern was implemented with STL container list. I have used the critical section protection in the Attach, Detach and Notify functions.
I deleted the observer objects before closing the UDP socket.
The data transfer rate may be a little faster than process data, because after closing the data source the data process is still working.
I can't figure out what lead my app can not exit completely. Please give me some clues.
This is usually caused by a thread you created and not exit it programmatically when you exit the appliation. There must be a while clause in your thread. The way to find where it is still running is:
use debug mode to start you application and click the exit button the top right corner to exit it.
Check from task manager and see if it is still running
if it is, excute Debug->Break All,
Open threads windows, double click each thread, you will find where your code is still looping.
Typically a process won't terminate because there's still a foreground thread running somewhere. You must ensure that your socket library isn't running any thread when you want to close your application.
First thing, with MFC, please use the notification based methods to get notifications on message arrivals, connections etc. So you can get rid of threads if you have.
It's quite easy to attache to a debugger and Break see which threads are existing and waiting for what.
Alternatively you can use ProcessExplorer with proper symbol configuration to see the call stacks of the threads available for the particular process.
The application can two kind of issues to exit, one could be infinite loop and other might be waiting/deadlock (e.g. socket read command is a blocking call). You can easily deduce the problem by attaching to debugger.
Otherwise please provide further information about the threads, code snippet possible.
I'm trying to write a Bluetooth server as a MFC app and while I got it working as a console app with blocking sockets, I can't get it working using CAsyncSocket.
The error it returns is 10035 - WSAEWOULDBLOCK as soon as I call Accept()
I could copy the code, but it's way too long, so I'll just outline the general idea:
- create, bind regular socket and start listening just like in the Microsoft SDK example app
- attach this socket to CAsyncSocket
- call Accept() (this is where the error occurs)
Any ideas how to get Bluetooth working with CAsyncSocket?
CAsyncSocket's OnAccept member function is called when you can Accept. Subclass CAsyncSocket and handle the OnAccept notification.
Thanks, I've corrected that, but OnAccept, OnConnect(), etc. were never executed, not even when called directly. It turned out that I had to delete all the temporary files the compiler and linker use to find out that I was using global shorthand function log() which clashed with log() defined in math.h and which caused some weird behavior.
See this thread for more datails http://www.codeguru.com/forum/showthread.php?t=339413
UPDATE: now you can download the finished app and the whole source code on Brm Bluetooth Remote Control homepage!
I'm writing a program that among other things needs to download a file given its URL. I'm too lazy to implement the Http/Https protocols manually, so that I needed some library/object/function that'll do the job.
Critical requirement: The download must be asynchronous. That is, the thread that issued the download must be able to do something else "while" downloading the file, plus the download must be able to be aborted anytime without any barbaric side effects (such as internal call to TerminateThread).
Nice-to-have requirements:
Should be able to download the file "into memory". Means - read the contents of the file as they arrive, not necessarily save it into some "file system" file.
It'd be nice to have some convenient Win32 progress notification mechanism (waitable event, semahpore, completion port, etc.), rather than just periodically polling the download status.
I've chosen the XmlHttpRequest COM object to do the work. It seemed to work fine enough, plus it supported asynchronous mode.
However I noticed that after some period it just stops working.
That is, after several successful file downloads it stops downloading anything.
I periodically poll it to get its status, it reports "in-progress", but nothing actually happens, and there's no network activity. Moreover, when the same process creates another instance of XmlHttpRequest object to perform new downloads - the effect is the same. The object reports "in progress", whereas it doesn't even try to connect to the server (according to network sniffers and system TCP state).
The only way to make this object work back is to restart the process. This makes me suspect that there's a sort of a bug (sorry, I meant undocumented feature) in the object. Also it's not a bug at the level of an individual object, since the problem persists when the object is destroyed and another one is created. It's probably some global state of the DLL that implements this object.
Does anyone know something about this? Is this a known bug?
I'm pretty sure there's no chance that I have another bug in my code, because of which it seems to me to be the bug is in the XmlHttpRequest. I've done enoughtests and spent time with the debugger to conclude without reasonable doubt that it's just the object stops working.
BTW, while the object should work, I do all the waiting via MsgWaitXXXX API calls. So that if this object needs the message loop to work properly (for instance, it may create a hidden notification window and bind it to a socket via WSAAsyncSelect) - I give it the opportunity.
I know from my own experiences that the Microsoft implementation of the XmlHttpRequest falls short of full compliance with the draft standard. In particular the standard mandates that streamed data should be able to be extracted in ready state '3' (Receiving) which IE deliberately ignores.
Unfortunately I have not seen what you are describing despite using XmlHttpRequest objects extensively for long polling purposes.