Problem writing Time-Out function

Alright this one might seem a little odd.  Basically when I initialize my
dialog I have to call a routine (RunSameThread) which unfortunately calls
some functions set with a library (which I don't have the source code for)
which may not exit.  (Basically this call should initialize the COM port and
send's some commands to a transceiver attached to the port, then wait for a
response before returning).  Now, if the transceiver is not hooked up (or
turned on) the COM port initialization will go though, but the library
function will sit in an infinite loop :(
Thus, I am trying to write a time-out function such that if so many seconds
go by and this function does not exit, I am going to shut the program down
and notify the user.

Here is how I am trying to do the above:
in my OnInitDialog I have:
SetTimer(IDT_TIMER_1, 4000, NULL);
if (!RunSameThread) {
    AfxMessageBox("Could not initialize COM port");
    exit(0);  //I do intend to put proper exit code here once I get the
above working :)
}
KillTimer(IDT_TIMER_1);

Then in my OnTimer() function I have

if (TimerVal==IDT_TIMER_1) {
    KillTIMER(IDT_TIMER_1);
    AfxMessageBox("Timed out waiting for sat response!");
    exit(0);
}

Logically I thought this would work as the timer is set up before I enter
the method RunSameThread(), and (using breakpoints) I know that the program
never gets past the line if (!RunSameThread) {   if the
satellite/transceiver is not connected.  Can anyone tell me first what I am
doing wrong (is it perhaps the case that the this timer will only fire if
the program is idle???).  And if someones knows of a better solution that
would work, could you please point me in the right direction (please just
remember that I cannot edit RunSameThread to fix this solution as it calls
functions which are in a compiled library (or dll I can't actually remember)
but that source code was proprietory? so we are forced to work around it :(
Thanks for your help!


0
Arlis
2/16/2004 4:02:52 PM
vc.mfc 33608 articles. 0 followers. Follow

4 Replies
524 Views

Similar Articles

[PageSpeed] 49

"Arlis Rose" <arlisATendevouraerospace.com> wrote in message
news:eTSEsZK9DHA.1548@tk2msftngp13.phx.gbl...
> Alright this one might seem a little odd.  Basically when I initialize my
> dialog I have to call a routine (RunSameThread) which unfortunately calls
> some functions set with a library (which I don't have the source code for)
> which may not exit.  (Basically this call should initialize the COM port
and
> send's some commands to a transceiver attached to the port, then wait for
a
> response before returning).  Now, if the transceiver is not hooked up (or
> turned on) the COM port initialization will go though, but the library
> function will sit in an infinite loop :(
> Thus, I am trying to write a time-out function such that if so many
seconds
> go by and this function does not exit, I am going to shut the program down
> and notify the user.
>
> Here is how I am trying to do the above:
> in my OnInitDialog I have:
> SetTimer(IDT_TIMER_1, 4000, NULL);
> if (!RunSameThread) {
>     AfxMessageBox("Could not initialize COM port");
>     exit(0);  //I do intend to put proper exit code here once I get the
> above working :)
> }
> KillTimer(IDT_TIMER_1);
>
> Then in my OnTimer() function I have
>
> if (TimerVal==IDT_TIMER_1) {
>     KillTIMER(IDT_TIMER_1);
>     AfxMessageBox("Timed out waiting for sat response!");
>     exit(0);
> }
>
> Logically I thought this would work as the timer is set up before I enter
> the method RunSameThread(), and (using breakpoints) I know that the
program
> never gets past the line if (!RunSameThread) {   if the
> satellite/transceiver is not connected.  Can anyone tell me first what I
am
> doing wrong (is it perhaps the case that the this timer will only fire if
> the program is idle???).  And if someones knows of a better solution that
> would work, could you please point me in the right direction (please just
> remember that I cannot edit RunSameThread to fix this solution as it calls
> functions which are in a compiled library (or dll I can't actually
remember)
> but that source code was proprietory? so we are forced to work around it
:(
> Thanks for your help!
>
>
Arlis,
    You can create an event object (CreateEvent) that will be signaled
when/if the infinite loop function exits.  You will have another thread
which will block on your event object (WaitForSingleObject) which will be
set when the inifinite loop function returns.  The call to
WaitForSingleObject will either time out when it hits your specified time
out value or it will return a valid value saying the function exited.

Pseudo C code:

thread1
{
....
create_nonsignaled_event;
call_long_function();
signal_event;
.....
}

thread2
{
waitforsingleobject(signal_event, 5000) // 5 sec or until function finishes
if (timed_out)
{
terminate_thread1 (TerminateThread)
}
}
}

Of course a better solution would be to find out what RS232 protocol is
being used and send some sort of ENQ byte if the protocol supports it.  For
example, if you were communicating with a modem and had some library
function which would hang if the modem was not attached, I would send "AT"
to the modem and wait for a certain period of time for the "OK" response
before trying to execute the infinite loop function.


0
trevor8021 (184)
2/16/2004 9:46:05 PM
The problem is that the timer will not fire until you get back to the main message pump,
which you won't do because the library blocks (it may or may not be in an "infinite
loop"). So this solution cannot work. Because the GUI thread is blocked, or possibly
looping, you will be unable to shut the application down or notify the user.

This is a really nasty problem. The best solution is to create a thread that calls the
library, and then wait for it to terminate. There are two ways to do this:
WaitForSingleObject on the thread handle with a timeout, which blocks the GUI thread, and
having the thread PostMessage a completion notification to your GUI thread and simply
return, having done a SetTimer. While the GUI is in a state of "waiting for thread", you
have to disable whatever commands, menu items, etc. that would cause problems if activated
during this time. But it would allow you to pop up a "Cancel" dialog so the user could
cancel the operation earlier if desired.

Now the nasty part: there is no good, accepted, reliable way to kill that thread. The only
option available at this point is to call TerminateThread, which can lead to serious
problems later (particularly if the library is an ActiveX control or some other control
which leaves bogus state around such that another incarnation of the control will
malfunction in a different way. It is impossible to predict or control what will go wrong.
Maybe nothing. Maybe nothing on your machine. Maybe nothing this week. Maybe nothing with
this release of the library.  And then again, you might get into a situation that causes
serious problems. You won't be able to tell what will happen. Or control it. Or recover
from it.

It would have been nice if the implementor of the library was prepared to deal with the
failure mode you describe, which should have been an expected failure mode. Alas, you are
not that fortunate.

When you have to deal with poorly-designed software like the library you are describing,
the ability to recover by doing "unapproved" things like TerminateThread will place you in
constant hazard. Essentially, the library is what we call Broken By Design, and you can
only hope that whatever approach you take will create a survivable situation. But there
are no guarantees in cases like this.
					joe

On Mon, 16 Feb 2004 11:02:52 -0500, "Arlis Rose" <arlisATendevouraerospace.com> wrote:

>Alright this one might seem a little odd.  Basically when I initialize my
>dialog I have to call a routine (RunSameThread) which unfortunately calls
>some functions set with a library (which I don't have the source code for)
>which may not exit.  (Basically this call should initialize the COM port and
>send's some commands to a transceiver attached to the port, then wait for a
>response before returning).  Now, if the transceiver is not hooked up (or
>turned on) the COM port initialization will go though, but the library
>function will sit in an infinite loop :(
>Thus, I am trying to write a time-out function such that if so many seconds
>go by and this function does not exit, I am going to shut the program down
>and notify the user.
>
>Here is how I am trying to do the above:
>in my OnInitDialog I have:
>SetTimer(IDT_TIMER_1, 4000, NULL);
>if (!RunSameThread) {
>    AfxMessageBox("Could not initialize COM port");
>    exit(0);  //I do intend to put proper exit code here once I get the
>above working :)
>}
>KillTimer(IDT_TIMER_1);
>
>Then in my OnTimer() function I have
>
>if (TimerVal==IDT_TIMER_1) {
>    KillTIMER(IDT_TIMER_1);
>    AfxMessageBox("Timed out waiting for sat response!");
>    exit(0);
>}
>
>Logically I thought this would work as the timer is set up before I enter
>the method RunSameThread(), and (using breakpoints) I know that the program
>never gets past the line if (!RunSameThread) {   if the
>satellite/transceiver is not connected.  Can anyone tell me first what I am
>doing wrong (is it perhaps the case that the this timer will only fire if
>the program is idle???).  And if someones knows of a better solution that
>would work, could you please point me in the right direction (please just
>remember that I cannot edit RunSameThread to fix this solution as it calls
>functions which are in a compiled library (or dll I can't actually remember)
>but that source code was proprietory? so we are forced to work around it :(
>Thanks for your help!
>

Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15974)
2/16/2004 11:21:38 PM
Thanks for your help Trevor and Joseph, I will look into the two ideas
presented see if either is the route I'm going to have to take.  Yes it's
very unfortunate that they didn't plan for this occurance, it's pretty
amazing when the library has such functions as heartbeat intervals (for
timeouts) and such, and yet can't recover from such a simple error as not
having the transceiver hooked up and/or power on.  Of course this means the
only way to kill the program if the transceiver is not available is to kill
the process using the task manager :( (big bad).  Ah well, I will try the
threading idea, see what kind of problems arrise if I kill it while it is
trying to connect to a non-existant transceiver.  Hopefully it won't cause
any problems (or perhaps I'll get lucks and the creators of the transceivers
code will upgrade their library :)
Thanks again for the advice.


0
Arlis
2/17/2004 1:25:52 PM
The problem arises with the interactions of TerminateThread with the rest of the state. It
has the same hazards as using the Task Manager to do the kill, that is, global OS state
that may have been modified will be corrupted. Example: if you terminate a thread or
process that has a multimedia device open, the device is forevermore (at least until the
next reboot) inaccessible, because the MM library is bug-ridden and cannot handle a
process simply terminating without doing a close. As would happen when you are debugging,
for example. TerminateThread may be harmless. But it may not be. It depends on what that
library is doing, and since you don't have the source, you can't tell for sure. It might
leave state around that necessitates exiting the program, and even then, there is global
OS state that might be left in strange states. The overall summary: it will probably work,
but don't complain if it leaves things weird. (Well, yes, complain to the people who wrote
the library. That failure mode is inexcusable).
						joe

On Tue, 17 Feb 2004 08:25:52 -0500, "Arlis Rose" <arlisATendevouraerospace.com> wrote:

>Thanks for your help Trevor and Joseph, I will look into the two ideas
>presented see if either is the route I'm going to have to take.  Yes it's
>very unfortunate that they didn't plan for this occurance, it's pretty
>amazing when the library has such functions as heartbeat intervals (for
>timeouts) and such, and yet can't recover from such a simple error as not
>having the transceiver hooked up and/or power on.  Of course this means the
>only way to kill the program if the transceiver is not available is to kill
>the process using the task manager :( (big bad).  Ah well, I will try the
>threading idea, see what kind of problems arrise if I kill it while it is
>trying to connect to a non-existant transceiver.  Hopefully it won't cause
>any problems (or perhaps I'll get lucks and the creators of the transceivers
>code will upgrade their library :)
>Thanks again for the advice.
>

Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
0
newcomer (15974)
2/17/2004 6:18:18 PM
Reply:

Similar Artilces:

Problem shortcuts in Word
Hello, I work with Word 2008. In the beginning there is no problem, but suddenly i have problem with shortcuts. When i want to do "cmd c" it make an other shortcuts same thing for "cmd s", "cmd v" and surly some other. But when i write there is no problem "c" is "c"... If somebody have an idea please help me. Thank you. Unless you indicate your specific update level of Office as well as OS X & describe what the keystrokes *are* doing contrary to what you expect there isn't much we can offer. -- Regards |:>)...

encoding problem in Outlook 2007 importing Outlook 2000 personal folders
I use Outlook 2007 to import the pst file of Outlook 2000. The Chinese characters in the subject became unreadable but it's ok to display in message body. In Outlook 2000, there's no problem to display the Chinese characters in the subject. What's wrong with Outlook 2007? What setttings should I change to fix the problem? Thanks. cyl <u8526505@gmail.com> wrote: > I use Outlook 2007 to import the pst file of Outlook 2000. The Chinese > characters in the subject became unreadable but it's ok to display in > message body. In Outlook 2000, there's no problem t...

Outlook 2003 PST problems
I just installed Office 2003 professional on a new computer & am having problems with outlook. I copied my Outlook.pst file into the appropriate directory & although it is recognized the calendar is not working properly. I cannot attach any of the colored labels to my appointments - so everything is pretty much in black & white. I totally uninstalled & reinstalled office... first removing my pst file... but there appears to be an ini file... or something that is retaining some information... does anyone know of a fix for the labels... or how to TOTALLY uninstall office (so I...

Problem with Authentication
The CRM application was running smooth. But now I can't logging. It ask my credentials and than return a 401.1 error. I had already reinstalled the CRM server but it won't work. I'm accessing it in the same local network. I'm running CRM 3.0 in SBS. Best regards, Erico Hi When you open a Internet explorer and type the name of the CRM server, it prompts for user and password ? Are you logged in with domain credentials ( AD user ) ? If you are, so add url of the crm server in Local intranet. Enable "Automatic logon only in intranet", this is under security,c...

Vista blue screen problem...please help!
I've seen some other threads, here are the dump files: 'RapidShare: 1-CLICK Web hosting - Easy Filehosting' (http://rapidshare.com/files/347103149/Minidump.rar.html) Please, help me out here. -- ceVil It might be better to know at what point the bsod occurs and what the actual err.msg given is "ceVil" <guest@unknown-email.com> wrote in message news:0b9a0c60b90bf6c0be88bda30f2820ab@nntp-gateway.com... > > I've seen some other threads, here are the dump files: > 'RapidShare: 1-CLICK Web hosting - Easy Filehosting' > (...

calendar problem
Dear all, I am using both mail and calendar function in outlook 2002. Everything is ok until recently, when I try to make a new appointment or checking any old appointments, an error message "out of memory or resource, try to close some windows..." pop up. The mail function is still ok. Can anyone tell me how can I solve this? I have already installed sp2. The version of office is the professional one with frontpage. Thanks. tp ...

problem #4
Hi, I am facing this new problem... i.e a user has installed Office 2003 on win2k prof platform.. whenever she is working on a outlook.. she gets a Microsoft error message... saying to send the report or don't send the report... Usually I have seen this problem in IE... But for outlook it is new to me... after clicking on send or don't send report.. the outlook closes. And there are no IE open..... and if atall it is open.. the IE does not close... Need your help regards, KAH What is logged to the Event Viewer regarding this? Try one of the following already; http://www.howt...

how to write vb code in access 2007
Version: MSAccess 2007 I have 3 fields in my database that contain currency. Field 1: PrincipleAmount Field 2: AmountPaid Field 3: AmountDue I have added a Command Button (cmdCalc) to the form. I need to write code that Subtracts Field2 from Field1 and returns the Balance in Field 3. I have no idea on how to gain access to and how to write code in MSAccess 2007. I can do this in VB6. Thanking You in Anticipation Julian On 15 dec, 13:29, tjbvo <tj...@discussions.microsoft.com> wrote: > Version: MSAccess 2007 > > I have 3 fields in my database that conta...

95 and 97 problem
For some unknown reason there is Excel 95 and 97 on this pc.When i double click on an Excel file, the pc defaults to the 95 program (Which incidently doesn't work properly). So my question is how do i get the pc to default to 97. Cheers Craig Craig, Have a look at Windows Help. From Windows 2000 Help (Index under Programs Associating with File Types) To change which program starts when you open a file In My Computer or Windows Explorer, on the View menu, click Folder Options. Click the File Types tab. In the list of file types, click the one you want to change. Click Edit. In Act...

Date problem
I can't believe there's no post on this, but I can't find it. I've tried the solutions I could find (see below) and still get the error: "The expression is typed incorrectly or it is too complex to be evaluated. For example....Try simplifying...." I have a date field, formatted as Date/Time, General Date, default Value = Now(). I like having the date and the time - in case we need it. I want to run a report on calls taken just for one day. I have CallDate: CallDateAndTime in my query, with "criteria" as Between ([Forms]![frmReports]![txtStartDate]) A...

sync problems
I have all of my info on an HP Ipac. I had to reformat the hard drive and I did not make a back-up file. I am trying to move everything back to the computer but it says there is an error with syncing it. How can I move everything from the PDA back to Outlook again? Please help- thanks ...

Office 2007 - HELP
I have used Word for many years and love it - not too thrilled with the changes in Office 2007, but my bigger issue is with Publisher 2007. I have an image that I have used in Word just fine - meaning, the on screen colors are correct and when printed the colors are correct. Someone sent me a Publisher file and asked me to add the image - I did this - now the image is messed up - the colors are correct on screen, but when printed FROM MY computer the image colors are all wrong - but if I transport the file to a different computer it prints fine I have reinstalled Office - no good Any id...

Installation Problem!!
I am having a problem installing MSCRM 1.2. My configuration consists of a Domain Controller running Win 2000 Server SP4 . I am trying to install MSCRM on a member of the domain running Windows 2000 Server SP4. There is a DNS Server on the DC which is integrated with AD, and a SQL Server 2000 running on the Win 2K machine. The install errors out when CRM creates the root business with the message: Setup was unable to install Microsoft CRM Server. Setup was unable to provision your organization. Setup was unable to create the root business. The configuration of ASP.NET seems to be ok, the pr...

Problems Creating a disclaimer in Exchange 2003
I am trying to create a server based disclaimer that will stamp all of my smtp emails going to the internet. I have been following KB article 317680 with no luck. I get an error like the one below. Binding Display Name Specified: smtpscriptinghost ** Registration Failed ** Err.Number (HRESULT) = 0x1AD Err.Description = ActiveX component can't create object ProgID = cdo.ss_smtponarrival COM Category = {FF3CAA23-00B9-11d2-9DFB-00C04FA322BA} Corresponding Event = onarrival ** Have you registered your sink COM class on this machine? I am puttin...

Resource editor problems
Hello all, Under VC++ 7.1... Please consider these two lines: IDC_ARROW_ADD_CANCEL DISCARDABLE "res\\cur00004.cur" IDC_ARROW_ADD_CANCEL CURSOR DISCARDABLE "res\\cur00004.cur" The second is a hand-edited change to the first. Both will compile just fine in the resource compiler. However, after I use a text editor to make this change, I cannot open the .rc file in the resource editor. The resource editor issues the following error open attempting to open the .rc file: error RC2135 : file not found: CURSOR Can anyone shed light on what's going on here? Thanks, Dave ...

How to graph 2 stacked colums/date, both over time?
I need to create a stacked column graph which displays two stacked columns, for example the components of actual sales compared to the same components of projected sales over several time periods within the same graph. Does anyone know how to accomplish this? Thanks. Is this what you need? http://peltiertech.com/Excel/ChartsHowTo/ClusterStack.html - Jon ------- Jon Peltier, Microsoft Excel MVP Tutorials and Custom Solutions http://PeltierTech.com _______ "LTB @ Miami, OK" <LTBMiamiOK@discussions.microsoft.com> wrote in message news:2F55225F-98E8-4F0E-BF25-31BD42...

Directory Replication Problem #2
Hi, recently my Exchange Server directory database receives changes from other servers but does not send out its own changes. Check from the knowledge base, to correct the USN discrepancy need to use Authrest.exe (need to amke changes for about 100+ users). Does anybody know where to get this file 'Authrest.exe' for exchange server 5.5? Exchange server 5.5 CD only provide this file for ver.4.0. Have anyone use it before? Regards, "Sharon Tan" <sharon_tansk@yahoo.com.sg> wrote: >Hi, recently my Exchange Server directory database >receives changes from ot...

Cell Format
I have a spreadsheet with cells that I'm trying to type the date into. I type in the date exactly like this: 09/26/03. When I hit "enter" MS Excel displays "37890" in the cell. No matter what I do I can't the cell to show: 09/26/03. I think that somehow I need to "strip" the cell of what it's original format is, but I can't figure out how. I try to use the Date option in the format cell screen but it doesn't work. Curtis I tried this and it didn't work. I also tried the "Text to columns" feature. No success. >...

User Defined Variables in MS query cause a problem to import data
If I use user defined variables in MS query to import data into excel sheet, the query executes but no data gets imported into the excel sheet. If I get rid of the variable the results can be imported into the Excel sheet. ...

outlook web access redirect problem
hi, I have been trying to redirect outlook web access (OWA) from the IIS root folder to the /exchange folder. I have followed the instructions on going into the web site and redirecting to a folder but I just get the following URL when I browse to the root of my webserver : http://webmail/exchange/exchange - it's like it's doubling up somehow. I have it set to : A redirection to a URL redirect to: /exchange client will be sent to: A directory below URL entered I just can't work it out... any ideas... cheers Baronne Which instructions did you follow? I wrote the below articl...

Function "Workingdays" query error date
I am trying to calculate the number of days, excluding weekends, between two dates. I am using the "workingdays" VBA code. I have pasted the code in a module, naming it "mdlWorkingdays". The code is listed below along with a sample of the data. "mdlWorkingdays" Option Compare Database '*********** Code Start ************** Public Function Workingdays(Start_Date As Date, End_Date As Date) As Integer '.................................................................... ' Name: WorkingDays ' Inputs: StartDate As Date ' EndDate As Da...

How do I do a TODAY() Function within a Nested IF AND Function
Hi, I'm trying to create a nested IF AND function. The difficulty I'm having is getting the function to calculate/include just the rows that have a date that is later than or equal to today. The "today" date would move as the file is opened and updated. The difficulty I'm having with it, though, is that it's calculating the rows that are blank or those that a date has been provided, but not just the date which is today or later. My current formula looks like: =IF(AND($C13=$B$13,$BV13>=TODAY()),$CJ13,"") Thanks, Jennifer C...

Problem after sorting
In my Excel 2007 workbook I have two sheets The "Master Names" sheet has columns: (A) First|(B) Last (C) First (B) Last (concatenated) The "Selected Names" sheet contains (A) cells which link to selected (C) First Last (concatenated) cells in the Master Names sheet. Everything links and displays fine except when I add names to the bottom of the Master Names sheet and then sort using (B) Last name column. When I do this I get a 0 (zero) in the (A) First Second cells in the Selected names sheet and other cells in this sheet have the wrong name. Obviously I am doin...

IF AND problem
Need to isolate problems on 1600 rows Worksheet Row Dept Hrs. Dollars A5 120500 600 9000 A6 120600 400 8000 A7 130600 240 A8 130400 160 A9 140600 320 6400 A10 140200 100 2000 A11 140600 240 (Found out the dept has 2 leading blanks) Isolate problems on 0600 criteria pointing out when b has value and c = 0. OK if both are 0. A7 and A11 should stand out.. =IF((MID(A1,5,4)="0600")=AND(b1>=0=AND(c1>=0)),"NO","ok") Does this work for you: =IF(RIGHT(A...

Problem SHAppBarMessage
Hi, I am creating an application bar which shall be displayed always at the top of the screen to show the user certain alerts. I am using the commands SHAppBarMessage(ABM_NEW, &abd); SHAppBarMessage(ABM_QUERYPOS, &abd); SHAppBarMessage(ABM_SETPOS, &abd); SetWindowPos(NULL, abd.rc.left, abd.rc.top, abd.rc.right - abd.rc.left, iClientHeight, SWP_NOACTIVATE); Works fine. The problem begins, when I start moving the taskbar. I am catching the event OnSettingChange and my application bar is resizing/moving correctly. BUT: If the taskbar moves to the top and my application bar ...