Why doesn't XOpenDisplay() fail with bad display names - c

Can anybody explain to me why XOpenDisplay() doesn't fail with bad display names? As long as the names follow the syntax convention, it always seems to succeed - even if the specified host name doesn't exist. XOpenDisplay() only seems to fail if the string uses a bad syntax, e.g.
d = XOpenDisplay("foobar"); // fails - presumably because of bad syntax in string
d = XOpenDisplay("foobar:0.0"); // works - although there is no host named "foobar"
When specifying a hostname that doesn't exist, XOpenDisplay() seems to fallback to $DISPLAY. Is that how it is supposed to be? I didn't find anything about these fallbacks in the Xlib documentation. If it is correct behaviour, is there a way to check whether the returned display really connected me to "foobar:0.0" or whether it is just a fallback to $DISPLAY?

That does seem like rather weak behavior, but http://tronche.com/gui/x/xlib/display/opening.html says:
The encoding and interpretation of the display name is implementation
dependent.
So it seems that this "interpretation" is allowed.
To tell if the default display was opened instead, you might try:
d_default = XOpenDisplay(NULL);
d = XOpenDisplay("foobar:0.0");
if (!d || d == d_default) {
// foobar:0.0 was not opened.
}
If this doesn't work because d and d_default are different even though referring to the same hardware, you might try comparing a field of the _XDisplay struct instead of the returned pointers, which are apparently pointing to different structs which somewhere must have similar data since they reference the same hardware. See the following reference for possibilities, but the simplest (if it works) might be to see if d->fd == d_default->fd.
Reference: http://xwindow.angelfire.com/page28.html

The only way I know of to force connection to a particular display is to stick the desired display name into the environment:
setenv("DISPLAY", "foobar:0.0", 1);
d = XOpenDisplay(0);
This is generally also desirable as the proper display name is also propagated to any child processes that are started, though if you want to avoid that, you could record the old $DISPLAY and restore it afterwards.

Related

duplicate "lo0" scopes, one of which hangs on attempts to connect()

My cross-platform C program takes an IPv6 address and port number, and tries to connect to the remote server they designate. The address may or may not have a scope suffix.
I use getifaddrs() and iterate through the results using a pointer struct ifaddr * pAdapter, ignoring the entries where pAdapter->ifa_addr->sa_family != AF_INET6.
If the user supplied a numeric scope suffix, I only look at entries where the scope ID (sockaddr_in6 *)(pAdapter->ifa_addr)->sin6_scope_id matches it, and if they supplied a non-numeric suffix, I only look at the entries where pAdapter->ifa_name matches it. But if the scope suffix was empty, I simply try all of the entries in turn, and the user has to live with the first successful one whichever it is. (This iteration seems unnecessary on Windows 10—from what I can tell, winsock2 seems to actually do its own similar cascade of attempts under the hood if you leave the scope ID and flow-control fields zeroed.)
On each attempt, I take a copy of *(sockaddr_in6 *)(pAdapter->ifa_addr), fill in the desired sin6_addr and sin6_port, and try to connect() my socket. On my Ubuntu box, this works. On Windows 10, it also works, though it's probably redundant as I mentioned. But on MacBooks running system 10.13.6 and 11.2.3, I have a problem: for some reason there are two IPv6 interfaces both called "lo0", one with scope ID 0 and one with scope ID 1, and connect() hangs when trying through the latter.
For example, I might be trying to connect to fe80::dead:beef%en0 (scope ID 5) and I only supply fe80::dead:beef. The fe80::dead:beef%0 attempt fails with "No route to host" and we move on, but the fe80::dead:beef%1 attempt hangs indefinitely and we never get as far as scope 5.
Why the duplication, why does it hang, and what should I do? Merely adding a timeout to the attempt would make the whole thing prohibitively slow. Is there any other way I determine that scope 1 is not a viable option, and move on?

Why is the windows return code called HRESULT?

The standard return type for functions in Windows C/C++ APIs is called HRESULT.
What does the H mean?
Result handle as stated here at MSDN Error Handling in COM
The documentation only says:
The return value of COM functions and methods is an HRESULT, which is not a handle to an object, but is a 32-bit value with several fields encoded in a single 32-bit ULONG variable.
Which seems to indicate that it stands for "handle", but is misused in this case.
Hex Result.
HRESULT are listed in the form of 0x80070005. They are a number that gets returned by COM\OLE calls to indicate various types of SUCCESS or FAILURE. The code itself is comprised of a bit field structure for those that want to delve into the details.
Details of the bit field structure can be found here at Microsoft Dev Center's topic Structure of COM Error Codes and here at MSDN HRESULT Structure.
The H-prefix in Windows data types generally designates handle types1 (such as HBRUSH or HWND). The documentation seems to be in agreement, sort of:
The HRESULT (for result handle) is a way of returning success, warning, and error values. HRESULTs are really not handles to anything; they are only values with several fields encoded in the value.
In other words: Result handles are really not handles to anything. Clearly, things cannot possibly have been designed to be this confusing. There must be something else going on here.
Luckily, historian Raymond Chen is incessantly conserving this kind of knowledge. In the entry aptly titled Why does HRESULT begin with H when it’s not a handle to anything? he writes:
As I understand it, in the old days it really was a handle to an object that contained rich error information. For example, if the error was a cascade error, it had a link to the previous error. From the result handle, you could extract the full history of the error, from its origination, through all the functions that propagated or transformed it, until it finally reached you.
The document concludes with the following:
The COM team decided that the cost/benefit simply wasn’t worth it, so the HRESULT turned into a simple number. But the name stuck.
In summary: HRESULT values used to be handle types, but aren't handle types any more. The entire information is now encoded in the value itself.
Bonus reading:
Handle types losing their reference semantics over time is not without precedent. What is the difference between HINSTANCE and HMODULE? covers another prominent example.
1 Handle types store values where the actual value isn't meaningful by itself; it serves as a reference to other data that's private to the implementation.

Sorting and managing numerous variables

My project has classes which, unavoidably, contain hundreds upon hundreds of variables that I'm always having to keep straight. For example, I'm always having to keep track of specific kinds of variables for a recurring set of "items" that occur inside of a class, where placing those variables between multiple classes would cause a lot of confusion.
How do I better sort my variables to keep from going crazy, especially when it comes time to save my data?
Am I missing something? Actionscript is an Object Oriented language, so you might have hundreds of variables, but unless you've somehow treated it like a grab bag and dumped it all in one place, everything should be to hand. Without knowing what all you're keeping track of, it's hard to give concrete advice, but here's an example from a current project I'm working on, which is a platform for building pre-employment assessments.
The basic unit is a Question. A Question has a stem, text that can go in the status bar, a collection of answers, and a collection of measures of things we're tracking about what the user does in that particular type of questions.
The measures are, again, their own type of object, and come in two "flavors": one that is used to track a time limit and one that isn't. The measure has a name (so we know where to write back to the database) and a value (which tells us what). Timed ones also have a property for the time limit.
When we need to time the question, we hand that measure to yet another object that counts the time down and a separate object that displays the time (if appropriate for the situation). The answers, known as distractors, have a label and a value that they can impart to the appropriate measure based on the user selection. For example, if a user selects "d", its value, "4" is transferred to the measure that stores the user's selection.
Once the user submits his answer, we loop through all the measures for the question and send those to the database. If those were not treated as a collection (in this case, a Vector), we'd have to know exactly what specific measures are being stored for each question and each question would have a very different structure that we'd have to dig through. So if looping through collections is your issue, I think you should revisit that idea. It saves a lot of code and is FAR more efficient than "var1", "var2", "var3."
If the part you think is unweildy is the type checking you have to do because literally anything could be in there, then Vector could be a good solution for you as long as you're using at least Flash Player 10.
So, in summary:
When you have a lot of related properties, write a Class that keeps all of those related bits and pieces together (like my Question).
When objects have 0-n "things" that are all of the same or very similar, use a collection of some sort, such as an Array or Vector, to allow you to iterate through them as a group and perform the same operation on each (for example, each Question is part of a larger grouping that allows each question to be presented in turn, and each question has a collection of distractors and another of measures.
These two concepts, used together, should help keep your information tidy and organized.
While I'm certain there are numerous ways of keeping arrays straight, I have found a method that works well for me. Best of all, it collapses large amounts of information into a handful of arrays that I can parse to an XML file or other storage method. I call this method my "indexed array system".
There are actually multiple ways to do this: creating a handful of 1-dimensional arrays, or creating 2-dimensional (or higher) array(s). Both work equally well, so choose the one that works best for your code. I'm only going to show the 1-dimensional method here. Those of you who are familiar with arrays can probably figure out how to rewrite this to use higher dimensional arrays.
I use Actionscript 3, but this approach should work with almost any programming or scripting language.
In this example, I'm trying to keep various "properties" of different "activities" straight. In this case, we'll say these properties are Level, High Score, and Play Count. We'll call the activities Pinball, Word Search, Maze, and Memory.
This method involves creating multiple arrays, one for each property, and creating constants that hold the integer "key" used for each activity.
We'll start by creating the constants, as integers. Constants work for this, because we never change them after compile. The value we put into each constant is the index the corresponding data will always be stored at in the arrays.
const pinball:int = 0;
const wordsearch:int = 1;
const maze:int = 2;
const memory:int = 3;
Now, we create the arrays. Remember, arrays start counting from zero. Since we want to be able to modify the values, this should be a regular variable.
Note, I am constructing the array to be the specific length we need, with the default value for the desired data type in each slot. I've used all integers here, but you can use just about any data type you need.
var highscore:Array = [0, 0, 0, 0];
var level:Array = [0, 0, 0, 0];
var playcount:Array = [0, 0, 0, 0];
So, we have a consistent "address" for each property, and we only had to create four constants, and three arrays, instead of 12 variables.
Now we need to create the functions to read and write to the arrays using this system. This is where the real beauty of the system comes in. Be sure this function is written in public scope if you want to read/write the arrays from outside this class.
To create the function that gets data from the arrays, we need two arguments: the name of the activity and the name of the property. We also want to set up this function to return a value of any type.
GOTCHA WARNING: In Actionscript 3, this won't work in static classes or functions, as it relies on the "this" keyword.
public function fetchData(act:String, prop:String):*
{
var r:*;
r = this[prop][this[act]];
return r;
}
That queer bit of code, r = this[prop][this[act]], simply uses the provided strings "act" and "prop" as the names of the constant and array, and sets the resulting value to r. Thus, if you feed the function the parameters ("maze", "highscore"), that code will essentially act like r = highscore[2] (remember, this[act] returns the integer value assigned to it.)
The writing method works essentially the same way, except we need one additional argument, the data to be written. This argument needs to be able to accept any
GOTCHA WARNING: One significant drawback to this system with strict typing languages is that you must remember the data type for the array you're writing to. The compiler cannot catch these type errors, so your program will simply throw a fatal error if it tries to write the wrong value type.
One clever way around this is to create different functions for different data types, so passing the wrong data type in an argument will trigger a compile-time error.
public function writeData(act:String, prop:String, val:*):void
{
this[prop][this[act]] = val;
}
Now, we just have one additional problem. What happens if we pass an activity or property name that doesn't exist? To protect against this, we just need one more function.
This function will validate a provided constant or variable key by attempting to access it, and catching the resulting fatal error, returning false instead. If the key is valid, it will return true.
function validateName(ID:String):Boolean
{
var checkthis:*
var r:Boolean = true;
try
{
checkthis = this[ID];
}
catch (error:ReferenceError)
{
r = false;
}
return r;
}
Now, we just need to adjust our other two functions to take advantage of this. We'll wrap the function's code inside an if statement.
If one of the keys is invalid, the function will do nothing - it will fail silently. To get around this, just put a trace (a.k.a. print) statement or a non-fatal error in the else construct.
public function fetchData(act:String, prop:String):*
{
var r:*;
if(validateName(act) && validateName(prop))
{
r = this[prop][this[act]];
return r;
}
}
public function writeData(act:String, prop:String, val:*):void
{
if(validateName(act) && validateName(prop))
{
this[prop][this[act]] = val;
}
}
Now, to use these functions, you simply need to use one line of code each. For the example, we'll say we have a text object in the GUI that shows the high score, called txtHighScore. I've omitted the necessary typecasting for the sake of the example.
//Get the high score.
txtHighScore.text = fetchData("maze", "highscore");
//Write the new high score.
writeData("maze", "highscore", txtHighScore.text);
I hope ya'll will find this tutorial useful in sorting and managing your variables.
(Afternote: You can probably do something similar with dictionaries or databases, but I prefer the flexibility with this method.)

Is it a bad idea to mix bool and ret codes

I have some programs which make heavy use of libraries with enumerations of error codes.
The kind where 0(first value of enum) is success and 1 is failure. In some cases I have my own helper functions that return bool indicating error, in other cases I bubble up the error enumeration. Unfortunately sometimes I mistake one for the other and things fail.
What would you recommend? Am I missing some warnings on gcc which would warn in these cases?
P.S. it feels weird to return an error code which is totally unrelated to my code, although I guess I could return -1 or some other invalid value.
Is it a bad idea? No, you should do what makes sense rather than following some abstract rule (the likes of which almost never cater for all situations you're going to encounter anyway).
One way I avoid troubles is to ensure that all boolean-returning function read like proper English, examples being isEmpty(), userFlaggedExit() or hasContent(). This is distinct from my normal verb-noun constructs like updateTables(), deleteAccount() or crashProgram().
For a function which returns a boolean indicating success or failure of a function which would normally follow that verb-noun construct, I tend to use something like deleteAccountWorked() or successfulTableUpdate().
In all those boolean-returning cases, I can construct an easily readable if statement:
if (isEmpty (list)) ...
if (deleteAccountWorked (user)) ...
And so on.
For non-boolean-returning functions, I still follow the convention that 0 is okay and all other values are errors of some sort. The use of intelligent function names usually means it's obvious as to which is which.
But keep in mind, that's my solution. It may or may not work for other people.
In the parts of the application that you control, and the parts that make up your external API I would say, choose one type of error handling and stick to it. Which type is less important, but be consistent. Otherwise people working on your code will not know what to expect and even you yourself will scratch you head when you get back to the code in a year or so ;)
If standardizing on a zero == error scheme, you can mix and match both enum and bool if you construct your tests like this:
err = some_func();
if !err...
Since the first enum evaluates to zero and also the success case it matches perfectly with bool error returns.
However, in general it is better to return an int (or enum) since this allows for the expansion of the error codes returned without modification of calling code.
I wouldn't say, that it's a bad practice.
There's no need to create tons of enum-s, if you just need to return true/false, and you don't have other options (and true and false are explanatory enough ).
Also, if your functions are named OK, you will have less "mistakes"
For example - IsBlaBla - expects to return true. If you have [Do|On]Reload, a reload could fail for many reasons, so enum would be expected. The same for IsConnected and Connect, etc.
IMHO function naming helps here.
E.g. for functions that return a boolean value, is_foo_bar(...), or for functions that return success or an error code, do_foo_bar(...).

How do I find a item in ListView control?

My list view contains 3 columns Name, address and phone number.
I want to retrieve an index for a particular name.
I'm using ListView_FindItem macro to find the index number but when my code comes to this line it crashes the program.
It just says Payroll has stopped working. Windows can check online for a solution to the problem.
I'm sure I have passed right handle to the ListView_FindItem macro but I'm not sure about the LVFINDINFO structure.
Here's my code
WCHAR szProcess[80] = {0};
LVFINDINFO item = {LVFI_STRING, (LPCTSTR) szProcess};
//code to find parent handles
...
//code to find index
index = ListView_FindItem(hwndListView, -1, &item);
I'm not sure about the LVFI_STRING flag and I have even tried passing a constant LVFINDINFO structure to ListView_FindItem macro still my program crashes.
Note : The above code is not part of
the payroll application. I mean to say
the payroll application has the
listview and I'm trying to search the
item from other application.
Can some one point me in a right direction ?
Thanks.
Your description is a little unclear, but I interpret it that you are sending LVM_FINDITEM message (via the ListView_FindItem() macro) to a window in a different process.
This simply does not work for this particular Windows message since it passes a pointer to a struct in the calling process which is meaningless when interpreted in the context of the other process (the payroll app that owns the list view).
To solve your problem you could allocate memory in the other process although this is quite a complex task. A commonly cited example of the technique is to be found in the Code Project article, Stealing Program's Memory.
Perhaps a simpler approach would be to use WM_COPYDATA which will marshal string data between processes. If that doesn't have enough flexibility then you'd need to find another IPC mechanism, e.g. named pipes.

Resources