Experiencing APR failure - c

I am using libapr, but some of their basic primitives seem to be not working well, presenting a very strange behaviour. Here is the code I am writing:
pr_pool_t *mp=NULL;
apr_file_t *fp = NULL;
apr_pollset_t *pollset=NULL;
apr_pollfd_t file_fd;
/*apr initialization*/
CuAssertIntEquals(ct,0,apr_initialize());
CuAssertIntEquals(ct,0,apr_pool_create(&mp,NULL));
/*opens file to test poll*/
CuAssertIntEquals(ct,0,apr_file_open(&fp, FILENAME,
APR_FOPEN_WRITE | APR_FOPEN_CREATE | APR_FOPEN_READ,
APR_FPROT_UREAD|APR_FPROT_UWRITE|APR_FPROT_UEXECUTE , mp));
/*creates pollset*/
CuAssertIntEquals(ct,0,apr_pollset_create(&pollset, 10,mp,0));
/*prepares poll fd...*/
file_fd.desc_type = APR_POLL_FILE;
file_fd.reqevents = APR_POLLIN|APR_POLLOUT;
file_fd.desc.f = fp;
file_fd.client_data = fp;
/*adds pollfd to pollset*/
CuAssertIntEquals(ct,0,apr_pollset_add(pollset, &file_fd));
Everything runs well, untill I get to apr_pollset_add(pollset, &file_fd) where it fails and returns the value 1.
If you analyse the source code of this function, you find it will never return 1. Actually 1 is returned as a system error, which using libapr routine apr_sterror is translated into: 'operation not permitted'.
I almost didn't sleep and eat trying to solve this problem, but without success. I really need to use this library.
Any help would be appreciated.

I found the problem.
I was polling a regular file. A regular file is always ready be read or written.
1 corresponds to operation not permitted which is set when poll_ctl is called.

Related

Monitor flashing when running a Windows SendInput API

Well, I certainly should go to python since I did several functions of this type, keyboard event and mouse event, but decide to try to learn the windows api.
My goal is to know when button 1 of the mouse is pressed.
I created this file in a very beginner way, it returns in mouseData only 0.
The curious thing is that whenever I run it, it flashes my monitor at short intervals in blinks, but between 1 second with it off. Very strange that, execution is not viable.
Could someone help me understand and try to execute to see if it is only here.
Code:
int main()
{
DWORD mouseData = 0;
MOUSEINPUT tagMouse;
tagMouse.dx = 0;
tagMouse.dy = 0;
tagMouse.mouseData = mouseData;
tagMouse.dwFlags = MOUSEEVENTF_XDOWN;
tagMouse.dwExtraInfo = 0;
INPUT tagInput;
tagInput.type = INPUT_MOUSE;
tagInput.mi = tagMouse;
while (true) {
if (GetAsyncKeyState(VK_DELETE)) break;
SendInput(1, &tagInput, sizeof(INPUT));
printf("KEYWORD: %d\n", mouseData);
Sleep(500);
}
system("pause");
return 0;
}
I can reproduce your reported 'symptoms' - and the effect is really brutal!
Now, while I cannot offer a full explanation, I can offer a fix! You have an uninitialized field in your tagMouse structure (the time member, which is a time-stamp used by the system). Setting this to zero (which tells the system to generate its own time-stamp) fixes the problem. So, just add this line to your other initializer statements:
//...
tagMouse.dwExtraInfo = 0;
tagMouse.time = 0; // Adding this line fixes it!
//...
Note: I, too, would appreciate a fuller explanation; however, an uninitialized field, to me, smells like undefined behaviour! I have tried a variety of other values (i.e. not zero) for the time field but haven't yet found one that works.
The discussion here on devblogs may help. This quote seems relevant:
And who knows what sort of havoc that will create if a program checks
the timestamps and notices that they are either from the future or
have traveled back in time.

Unique String generator

I want to make a program (network server-client).
One of the specification for this program is next:
The server will receive the sent packages and save it into a file, with a unique name (generated by the server at the moment the transfer starts.
Ex __tf_"unique_random_string".txt
I made a function that returns a pointer to a "unique" string created.
The problem is: If i stop the server and then start it again it will generate the same names.
Ex:this file names were generated and then i stopped the server.
__ft_apqfwk.txt
__ft_arzowk.txt
__ft_cdyggx.txt
I start it again and i try to generate 3 file names. Them will be the same.
Sorry for my english. I'm still learning it.
My function to generate this "unique string" is:
char *create_random_name(void)
{
const char charset[] = "abcdefghijklmnopqrstuvwxyz";
char *file_name;
int i=0;
int key;
if((file_name = malloc(16 * sizeof ( char )) ) == NULL)
{
printf("Failed to alloc memory space\n");
return NULL;
}
strcpy(file_name,"__ft_");
for(i=5 ; i<11 ; i++)
{
key = rand() % (int)(sizeof(charset)-1);
file_name[i]=charset[key];
}
strcat(file_name,".txt");
file_name[15] = '\0';
return file_name;
}
One option is saving to a file the names that have been used, and using them as a checklist. You also want to seed rand with something like srand(time(NULL)).
another is ignoring the randomisation, and just going in order, e.g. aaa, aab aac...aba ,abb etc. Again, save where your cycle is up to on a file.
Your question seems a little bit unclear but if you want to generate a unique string there are a couple of things you can consider:
Get System timestamp ( yyyy-MM-dd-HH-mm-ss-fff-tt)
Use Random function to generate a random number
Combine this with your function and I am sure you will get a unique string.
Hope it helps !
If it's available, you could avoid manually generating random names that might collide and let the system do it for you (and handle collision resolution by creating a new name) by using mkstemps. This is also safer because it opens the file for you, removing the risk of a random name being generated, verified to be unique, then trying to open it and discovering another thread/process raced in and created it.
char name[] = "/path/to/put/files/in/__ft_XXXXXX.txt";
int fd = mkstemps(name, strlen(".txt"));
if (fd == -1) { ... handle error ... }
After mkstemps succeeds, name will hold the path to the file (it's mutated in place, replacing the XXXXXX string), and fd will be an open file descriptor to that newly created file; if you need a FILE*, use fdopen to convert to a stdio type.
Before calling rand(),--- once and only once---, call srand(time()) to initialize the random number generator.
Before settling on any specific file name, call stat() to assure that file name does not already exist.

AudioFileCreateWithURL failed('wht?')

I'm trying to record sound using Audio Queue, but every time I want to write to file I get the message AudioFileCreateWithURL failed('wht?'). I haven't been able to find a corresponding solution to this error, for I haven't found a similar (wht?) error elsewhere. I acquired the code from Apple's official guide for Audio Queue programming and it looks like this:
char* filePath = "Users/linus/voicies/output.wav";
CFURLRef myFileURL = CFURLCreateFromFileSystemRepresentation( // 1
NULL, // 2
(const UInt8 *) filePath, // 3
strlen (filePath), // 4
false // 5
);
OSStatus err = AudioFileCreateWithURL(
myFileURL,
kAudioFileWAVEType,
&recordFormat,
kAudioFileFlags_EraseFile,
&recorder.recordFile
);
CheckError(err);
in which CheckError finds the corresponding error, which is (wht?). I have no idea what that means and what I must do to make it happen, since the code I have used is almost identical to the sample codes. I appreciate any kind of clue.

Error in output.println() on Processing

I'm trying to read some data from Processing and write it to a file. The data is correct, since I can plot it without problem. However, when I attempt to write it to a file it throws me the following error:
Error, disabling serialEvent() for /dev/ttyACM0
null
Specifically, I've found out where the problem is. It's in this function:
void serialEvent(Serial myPort) {
int inByte = myPort.read();
if (inByte >= 0 && inByte <= 255)
{
// This is what makes the problem arise
output.println("test: " + inByte);
// ...
}
}
I've even changed the line output.println(); with this and then the same function works, printing it to the correct file (but it's obviously not what I want):
// This does work
point(mouseX, mouseY);
output.println(mouseX);
Any idea where the problem might be? I'm using arduino and it passes values from 0 to 255 from serial. The values seem correct, since I can plot them without problem. I've also tried changing println() for print() with no luck.
EDIT. After some testing, I find this really odd. This works:
point(mouseX, mouseY);
output.println(inByte);
While, without the point(), it doesn't work (same error). As a temporary solution, I can put the output.println at the end of the function, but this is obviously not a long-term solution.
I ended up doing a simple check in my code:
if (output != null) {
output.println(t + " " + inByte);
}
It just works. However, I think that polymorphism would be even better here. Having an object that absorbs the text if the output is not initialized, and that prints it to the file if it is.
I had the same problem but here is my solution and it works perfectly.
at the beginning of the code write sth like this:
boolean outputInitialized = false;
after output = createWriter(filename.txt); put following:
outputInitialized = true;
the output.print function has to be included in an if-function:
if (outputInitialized) {
output.println(filename);
}

InternetReadFileEx gives 10035 and 1008 errors

I am trying to write an Asyncronous Wininet application. I read the data in my callback function in case of INTERNET_STATUS_REQUEST_COMPLETE and I handle the ERROR_IO_PENDING errors as well. But after some data read from internet, InternetReadFileEx function gives me 10035=WSAEWOULDBLOCK (A non-blocking socket operation could not be completed immediately) error. After that error I call InternetReadFileEx again and this time it gives me 1008=ERROR_NO_TOKEN (An attempt was made to reference a token that does not exist.) error. I think my design is not correct, and I receive these error because of that.
Here is a snippet of my code:
case INTERNET_STATUS_REQUEST_COMPLETE:
{
BOOL bAllDone= FALSE;
DWORD lastError;
do
{
//Create INTERNET_BUFFERS
char m_pbReadBuffer[4096];
INTERNET_BUFFERS BuffersIn;
ZeroMemory(&BuffersIn, sizeof(INTERNET_BUFFERS));
BuffersIn.dwStructSize = sizeof(INTERNET_BUFFERS);
BuffersIn.lpvBuffer = m_pbReadBuffer;
BuffersIn.dwBufferLength = 4096;
InternetReadFileEx(ReqContext->File, &BuffersIn, IRF_ASYNC, 1);
//HERE I GOT THOSE 10035 and 1008 ERRORS
lastError = GetLastError();
if(lastError == 997) // handling ERROR_IO_PENDING
break;//break the while loop
//append it to my ISTREAM
(ReqContext->savedStream)->Write(BuffersIn.lpvBuffer, BuffersIn.dwBufferLength, NULL);
if (BuffersIn.dwBufferLength == 0)
bAllDone = TRUE;
}while(bAllDone == FALSE);
//delete[] m_pbReadBuffer;
if(bAllDone == TRUE && lastError== 0)
{
//these are for passing the ISTREAM to the function which calls "InternetOpenUrl"
LARGE_INTEGER loc;
loc.HighPart = 0;
loc.LowPart = 0;
ReqContext->savedStream->Seek(loc, STREAM_SEEK_SET, NULL);
ReqContext->savedCallback->OnUrlDownloaded(S_OK, ReqContext->savedStream); //Tell silverlight ISTREAM is ready
ReqContext->savedStream->Release();
ReqContext->savedCallback->Release();
InternetCloseHandle(ReqContext->File);
InternetSetStatusCallback(ReqContext->Connection, NULL);
InternetCloseHandle(ReqContext->Connection);
delete[] ReqContext;
}
}
break;
Can anyone give me a hand to correct that?
Thanks everyone helping...
GetLastError() is only meaningful if InternetReadFileEx() (or any other API, for that matter) actually fails with an error. Otherwise, you will be processing an error from an earlier API call, giving your code a false illusion that an error happened when it really may not have. You MUST pay attention to API return values, but you are currently ignoring the return value of InternetReadFileEx().
Worse than that, though, you are using InternetReadFileEx() in async mode but you are using a receiving buffer that is local to the INTERNET_STATUS_REQUEST_COMPLETE callback handler. If InternetReadFileEx() fails with an ERROR_IO_PENDING error, the read is performed in the background and INTERNET_STATUS_REQUEST_COMPLETE will be triggered when the read is complete. However, when that error occurs, you are breaking your loop (even though the read is still in progress) and that buffer will go out of scope before the read is finished. While the reading is still in progress, the receiving buffer is still on the stack and InternetReadFileEx() is still writing to it, but it may get re-used for other things at the same time because your code moved on to do other things and did not wait for the read to finish.
You need to re-think your approach. Either:
remove the IRF_ASYNC flag, since that is how the rest of your callback code is expecting InternetReadFileEx() to behave.
re-write the code to operate in async mode correctly. Dynamically allocate the receive buffer (or at least store it somewhere else that remains in scope during the async reading), don't call IStream::Write() unless you actually have data to write (only when InternetReadFileEx() returned TRUE right away, or you get an INTERNET_STATUS_REQUEST_COMPLETE event with a success code from an earlier InternetReadFileEx()/ERROR_IO_PENDING call), etc.
There are plenty of online examples and tutorials that show how to use InternetReadFileEx() in async mode. Search around.

Resources