GNOME and KDE both have "display managers", GDM and KDM respectively, that do a large part in this. The purposes of a display manager are, basically, to run an X11 server (Xorg these days, Xfree86 or the original X server earlier) on every physical display, and to present login screens on them. Xdm is probably the oldest one.
Modern display managers have been extended to run multiple X11 servers on the same seat – for each user session, plus one for the login screen (the "greeter") itself. Only one of those sessions is active at any time and controls the graphics hardware; the others give it up. [1]
On Linux, the "virtual console" function is used for this – it's technically possible to switch between those sessions using widely-known CtrlAltF12345… keys, although you won't know which user's X11 display runs on which virtual console. [2]
There's usually another daemon, usually either ConsoleKit or 'systemd-logind', which does the job of keeping track of what users are logged in, for all kinds of text and graphical sessions (tty, ssh, X11, Wayland, &c).
The session itself does not actually need to do much; it only depends 'logind', and sometimes on a specific display manager.
If you want to display a list of users (like Unity does), the 'logind' or ConsoleKit daemons can be used via DBus to obtain a list of logged-in users, and to activate the chosen session. The current session should lock itself after doing so (e.g. by running the screensaver; GNOME and KDE both have the screen-lock integrated in the window manager itself).
In GNOME, there is no list of users, only a single "Switch Users" menu item. This uses libgdmgreeter
to activate the "login session" (the session that has the login screen) using 'logind' or ConsoleKit; if there isn't a "login session" running, libgdmgreeter contacts GDM over DBus to start a new one. I think this could be done by running the gdmflexiserver
command.
[1] Voluntarily, in the current Linux implementation at least; there are plans to make it stricter so that a system component would actually revoke the access. Similarly, if you the sessions run PulseAudio, it voluntarily gives up access to audio devices. With bare ALSA, there's nothing that would do so, so audio access with session switching is a game of luck. That is, even if the inactive sessions are unable to open the audio devices after 'logind' did its job, they still can play sound through previously-opened devices, and nothing can force to close them yet (until the kernel gains revoke()
support).
[2] The Linux virtual consoles are only available on the 0th "seat"; if you had more displays and keyboards connected, they could have their own X11 servers – look up the Fedora 19 multiseat demos – but they I guess cannot have session switching. But right now there's a lot of development in trying to make multiseat work, among other things.