X Session Management Library Version 1.0 X Consortium Standard X Version 11, Release 6.4

1. Overview of Session ManagementThe purpose of the X Session Management Protocol (XSMP) isto provide a uniform mechanism for users to save and restoretheir sessions. A session is a group of clients, each ofwhich has a particular state. The session is controlled bya network service called the session manager. The sessionmanager issues commands to its clients on behalf of theuser. These commands may cause clients to save their stateor to terminate. It is expected that the client will saveits state in such a way that the client can be restarted ata later time and resume its operation as if it had neverbeen terminated. A client’s state might include informationabout the file currently being edited, the current positionof the insertion point within the file, or the start of anuncommitted transaction. The means by which clients arerestarted is unspecified by this protocol.For purposes of this protocol, a client of the sessionmanager is defined as a connection to the session manager.A client is typically, though not necessarily, a processrunning an application program connected to an X display.However, a client may be connected to more than one Xdisplay or not be connected to any X displays at all.2. The Session Management LibraryThe Session Management Library (SMlib) is a low-level "C"language interface to XSMP. It is expected that higherlevel toolkits, such as Xt, will hide many of the details ofsession management from clients. Higher level toolkitsmight also be developed for session managers to use, but nosuch effort is currently under way.SMlib has two parts to it:• One set of functions for clients that want to be partof a session• One set of functions for session managers to callSome applications will use both sets of functions and act asnested session managers. That is, they will be both asession manager and a client of another session. An exampleis a mail program that could start a text editor for editingthe text of a mail message. The mail program is part of aregular session and, at the same time, is also acting as asession manager to the editor.Clients initialize by connecting to the session manager andobtaining a client-ID that uniquely identifies them in thesession. The session manager maintains a list of propertiesfor each client in the session. These properties describethe client’s environment and, most importantly, describe howthe client can be restarted (via an SmRestartCommand).Clients are expected to save their state in such a way as toallow multiple instantiations of themselves to be managedindependently. For example, clients may use their client-IDas part of a filename in which to store the state for aparticular instantiation. The client-ID should be saved aspart of the SmRestartCommand so that the client will retainthe same ID after it is restarted.Once the client initializes itself with the session manager,it must be ready to respond to messages from the sessionmanager. For example, it might be asked to save its stateor to terminate. In the case of a shutdown, the sessionmanager might give each client a chance to interact with theuser and cancel the shutdown.3. Understanding SMlib’s Dependence on ICEThe X Session Management Protocol is layered on top of theInter-Client Exchange (ICE) Protocol. The ICE protocol isdesigned to multiplex several protocols over a singleconnection. As a result, working with SMlib requires alittle knowledge of how the ICE library works.The ICE library utilizes callbacks to process messages.When a client detects that there is data to read on an ICEconnection, it should call the IceProcessMessages function.IceProcessMessages will read the message header and look atthe major opcode in order to determine which protocol themessage was intended for. The appropriate protocol librarywill then be triggered to unpack the message and hand it offto the client via a callback.The main point to be aware of is that an application usingSMlib must have some code that detects when there is data toread on an ICE connection. This can be done via a selectcall on the file descriptor for the ICE connection, but moretypically, XtAppAddInput will be used to register a callbackthat will invoke IceProcessMessages each time there is datato read on the ICE connection.To further complicate things, knowing which file descriptorsto call select on requires an understanding of how ICEconnections are created. On the client side, a call must bemade to SmcOpenConnection in order to open a connection witha session manager. SmcOpenConnection will internally make acall into IceOpenConnection, which will, in turn, determineif an ICE connection already exists between the client andsession manager. Most likely, a connection will not alreadyexist and a new ICE connection will be created. The mainpoint to be aware of is that, on the client side, it is notobvious when ICE connections get created or destroyed,because connections are shared when possible. To deal withthis, the ICE library lets the application register watchprocedures that will be invoked each time an ICE connectionis opened or closed. These watch procedures could be usedto add or remove ICE file descriptors from the list ofdescriptors to call select on.On the session manager side, things work a bit differently.The session manager has complete control over the creationof ICE connections. The session manager has to first callIceListenForConnections in order to start listening forconnections from clients. Once a connection attempt isdetected, IceAcceptConnection must be called, and thesession manager can simply add the new ICE file descriptorto the list of descriptors to call select on.For further information on the library functions related toICE connections, see the Inter-Client Exchange Librarystandard.4. Header Files and Library NameApplications (both session managers and clients) shouldinclude the header file <X11/SM/SMlib.h>. This header filedefines all of the SMlib data structures and functionprototypes. SMlib.h includes the header file <X11/SM/SM.h>,which defines all of the SMlib constants.Because SMlib is dependent on ICE, applications should linkagainst SMlib and ICElib by using -lSM -lICE.5. Session Management Client (Smc) FunctionsThis section discusses how Session Management clients:• Connect to the Session Manager• Close the connection• Modify callbacks• Set, delete, and retrieve Session Manager properties• Interact with the user• Request a ‘‘Save Yourself’’• Request a ‘‘Save Yourself Phase 2’’• Complete a ‘‘Save Yourself’’• Use Smc informational functions• Handle Errors5.1. Connecting to the Session ManagerTo open a connection with a session manager, useSmcOpenConnection.__│ SmcConn SmcOpenConnection(network_ids_list, context, xsmp_major_rev, xsmp_minor_rev,mask, callbacks, previous_id, client_id_ret, error_length, error_string_ret)char *network_ids_list;SmPointer context;int xsmp_major_rev;int xsmp_minor_rev;unsigned long mask;SmcCallbacks *callbacks;char *previous_id;char **client_id_ret;int error_length;char *error_string_ret;network_ids_listSpecifies the network ID(s) of the sessionmanager.context A pointer to an opaque object or NULL. Used todetermine if an ICE connection can be shared (seebelow).xsmp_major_revThe highest major version of the XSMP theapplication supports.xsmp_minor_revThe highest minor version of the XSMP theapplication supports (for the specifiedxsmp_major_rev).mask A mask indicating which callbacks to register.callbacks The callbacks to register. These callbacks areused to respond to messages from the sessionmanager.previous_idThe client ID from the previous session.client_id_retThe client ID for the current session is returned.error_lengthLength of the error_string_ret argument passed in.error_string_retReturns a null-terminated error message, if any.The error_string_ret argument points to usersupplied memory. No more than error_length bytesare used.│__The network_ids_list argument is a null-terminated stringcontaining a list of network IDs for the session manager,separated by commas. If network_ids_list is NULL, the valueof the SESSION_MANAGER environment variable will be used.Each network ID has the following format:An attempt will be made to use the first network ID. Ifthat fails, an attempt will be made using the second networkID, and so on.After the connection is established, SmcOpenConnectionregisters the client with the session manager. If theclient is being restarted from a previous session,previous_id should contain a null terminated stringrepresenting the client ID from the previous session. Ifthe client is first joining the session, previous_id shouldbe set to NULL. If previous_id is specified but isdetermined to be invalid by the session manager, SMlib willre-register the client with previous_id set to NULL.If SmcOpenConnection succeeds, it returns an opaqueconnection pointer of type SmcConn and the client_id_retargument contains the client ID to be used for this session.The client_id_ret should be freed with a call to free whenno longer needed. On failure, SmcOpenConnection returnsNULL, and the reason for failure is returned inerror_string_ret.Note that SMlib uses the ICE protocol to establish aconnection with the session manager. If an ICE connectionalready exists between the client and session manager, itmight be possible for the same ICE connection to be used forsession management.The context argument indicates how willing the client is toshare the ICE connection with other protocols. If contextis NULL, then the caller is always willing to share theconnection. If context is not NULL, then the caller is notwilling to use a previously opened ICE connection that has adifferent non-NULL context associated with it.As previously discussed (section 3, ‘‘Understanding SMlib’sDependence on ICE’’), the client will have to keep track ofwhen ICE connections are created or destroyed (usingIceAddConnectionWatch and IceRemoveConnectionWatch), andwill have to call IceProcessMessages each time a selectshows that there is data to read on an ICE connection. Forfurther information, see the Inter-Client Exchange Librarystandard.The callbacks argument contains a set of callbacks used torespond to session manager events. The mask argumentspecifies which callbacks are set. All of the callbacksspecified in this version of SMlib are mandatory. The maskargument is necessary in order to maintain backwardscompatibility in future versions of the library.The following values may be ORed together to obtain a maskvalue:SmcSaveYourselfProcMaskSmcDieProcMaskSmcSaveCompleteProcMaskSmcShutdownCancelledProcMaskFor each callback, the client can register a pointer toclient data. When SMlib invokes the callback, it will passthe client data pointer.__│ typedef struct {struct {SmcSaveYourselfProc callback;SmPointer client_data;} save_yourself;struct {SmcDieProc callback;SmPointer client_data;} die;struct {SmcSaveCompleteProc callback;SmPointer client_data;} save_complete;struct {SmcShutdownCancelledProc callback;SmPointer client_data;} shutdown_cancelled;} SmcCallbacks;│__5.1.1. The Save Yourself CallbackThe Save Yourself callback is of type SmcSaveYourselfProc.__│ typedef void (*SmcSaveYourselfProc)();void SaveYourselfProc(smc_conn, client_data, save_type, shutdown, interact_style, fast)SmcConn smc_conn;SmPointer client_data;int save_type;Bool shutdown;int interact_style;Bool fast;smc_conn The session management connection object.client_dataClient data specified when the callback wasregistered.save_type Specifies the type of information that should besaved.shutdown Specifies if a shutdown is taking place.interact_styleThe type of interaction allowed with the user.fast If True, the client should save its state asquickly as possible.│__The session manager sends a ‘‘Save Yourself’’ message to aclient either to checkpoint it or just before termination sothat it can save its state. The client responds with zeroor more calls to SmcSetProperties to update the propertiesindicating how to restart the client. When all theproperties have been set, the client callsSmcSaveYourselfDone.If interact_style is SmInteractStyleNone, the client mustnot interact with the user while saving state. Ifinteract_style is SmInteractStyleErrors, the client mayinteract with the user only if an error condition arises.If interact_style is SmInteractStyleAny, then the client mayinteract with the user for any purpose. Because only oneclient can interact with the user at a time, the client mustcall SmcInteractRequest and wait for an ‘‘Interact’’ messagefrom the session manager. When the client is doneinteracting with the user, it calls SmcInteractDone. Theclient may only call SmcInteractRequest after it receives a‘‘Save Yourself’’ message and before it callsSmcSaveYourselfDone.If save_type is SmSaveLocal, the client must update theproperties to reflect its current state. Specifically, itshould save enough information to restore the state as seenby the user of this client. It should not affect the stateas seen by other users. If save_type is SmSaveGlobal, theuser wants the client to commit all of its data topermanent, globally accessible storage. If save_type isSmSaveBoth, the client should do both of these (it shouldfirst commit the data to permanent storage before updatingits properties).Some examples are as follows:• If a word processor were sent a ‘‘Save Yourself’’ witha type of SmSaveLocal, it could create a temporary filethat included the current contents of the file, thelocation of the cursor, and other aspects of thecurrent editing session. It would then update itsSmRestartCommand property with enough information tofind this temporary file.• If a word processor were sent a ‘‘Save Yourself’’ witha type of SmSaveGlobal, it would simply save thecurrently edited file.• If a word processor were sent a ‘‘Save Yourself’’ witha type of SmSaveBoth, it would first save the currentlyedited file. It would then create a temporary filewith information such as the current position of thecursor and what file is being edited. Finally, itwould update its SmRestartCommand property with enoughinformation to find the temporary file.The shutdown argument specifies whether the system is beingshut down. The interaction is different depending onwhether or not shutdown is set. If not shutting down, theclient should save its state and wait for a ‘‘SaveComplete’’ message. If shutting down, the client must savestate and then prevent interaction until it receives eithera ‘‘Die’’ or a ‘‘Shutdown Cancelled.’’The fast argument specifies that the client should save itsstate as quickly as possible. For example, if the sessionmanager knows that power is about to fail, it would set fastto True.5.1.2. The Die CallbackThe Die callback is of type SmcDieProc.__│ typedef void (*SmcDieProc)();void DieProc(smc_conn, client_data)SmcConn smc_conn;SmPointer client_data;smc_conn The session management connection object.client_dataClient data specified when the callback wasregistered.│__The session manager sends a ‘‘Die’’ message to a client whenit wants it to die. The client should respond by callingSmcCloseConnection. A session manager that behaves properlywill send a ‘‘Save Yourself’’ message before the ‘‘Die’’message.5.1.3. The Save Complete CallbackThe Save Complete callback is of type SmcSaveCompleteProc.__│ typedef void (*SmcSaveCompleteProc)();void SaveCompleteProc(smc_conn, client_data)SmcConn smc_conn;SmPointer client_data;smc_conn The session management connection object.client_dataClient data specified when the callback wasregistered.│__When the session manager is done with a checkpoint, it willsend each of the clients a ‘‘Save Complete’’ message. Theclient is then free to change its state.5.1.4. The Shutdown Cancelled CallbackThe Shutdown Cancelled callback is of typeSmcShutdownCancelledProc.__│ typedef void (*SmcShutdownCancelledProc)();void ShutdownCancelledProc(smc_conn, client_data)SmcConn smc_conn;SmPointer client_data;smc_conn The session management connection object.client_dataClient data specified when the callback wasregistered.│__The session manager sends a ‘‘Shutdown Cancelled’’ messagewhen the user cancelled the shutdown during an interaction(see section 5.5, ‘‘Interacting With the User’’). Theclient can now continue as if the shutdown had neverhappened. If the client has not called SmcSaveYourselfDoneyet, it can either abort the save and then callSmcSaveYourselfDone with the success argument set to False,or it can continue with the save and then callSmcSaveYourselfDone with the success argument set to reflectthe outcome of the save.5.2. Closing the ConnectionTo close a connection with a session manager, useSmcCloseConnection.__│ SmcCloseStatus SmcCloseConnection(smc_conn, count, reason_msgs)SmcConn smc_conn;int count;char **reason_msgs;smc_conn The session management connection object.count The number of reason messages.reason_msgsThe reasons for closing the connection.│__The reason_msgs argument will most likely be NULL ifresignation is expected by the client. Otherwise, itcontains a list of null-terminated Compound Text stringsrepresenting the reason for termination. The sessionmanager should display these reason messages to the user.Note that SMlib used the ICE protocol to establish aconnection with the session manager, and various protocolsother than session management may be active on the ICEconnection. When SmcCloseConnection is called, the ICEconnection will be closed only if all protocols have beenshutdown on the connection. Check the ICElib standard forIceAddConnectionWatch and IceRemoveConnectionWatch to learnhow to set up a callback to be invoked each time an ICEconnection is opened or closed. Typically this callbackadds/removes the ICE file descriptor from the list of activedescriptors to call select on (or calls XtAppAddInput orXtRemoveInput).SmcCloseConnection returns one of the following values:• SmcClosedNow − the ICE connection was closed at thistime, the watch procedures were invoked, and theconnection was freed.• SmcClosedASAP − an IO error had occurred on theconnection, but SmcCloseConnection is being calledwithin a nested IceProcessMessages. The watchprocedures have been invoked at this time, but theconnection will be freed as soon as possible (when thenesting level reaches zero and IceProcessMessagesreturns a status ofIceProcessMessagesConnectionClosed).• SmcConnectionInUse − the connection was not closed atthis time, because it is being used by other activeprotocols.5.3. Modifying CallbacksTo modify callbacks set up in SmcOpenConnection, useSmcModifyCallbacks.__│ void SmcModifyCallbacks(smc_conn, mask, callbacks)SmcConn smc_conn;unsigned long mask;SmcCallbacks *callbacks;smc_conn The session management connection object.mask A mask indicating which callbacks to modify.callbacks The new callbacks.│__When specifying a value for the mask argument, the followingvalues may be ORed together:SmcSaveYourselfProcMaskSmcDieProcMaskSmcSaveCompleteProcMaskSmcShutdownCancelledProcMask5.4. Setting, Deleting, and Retrieving Session ManagementPropertiesTo set session management properties for this client, useSmcSetProperties.__│ void SmcSetProperties(smc_conn, num_props, props)SmcConn smc_conn;int num_props;SmProp **props;smc_conn The session management connection object.num_props The number of properties.props The list of properties to set.│__The properties are specified as an array of propertypointers. Previously set property values may beover-written using the SmcSetProperties function. Note thatthe session manager is not expected to restore propertyvalues when the session is restarted. Because of this,clients should not try to use the session manager as adatabase for storing application specific state.For a description of session management properties and theSmProp structure, see section 7, ‘‘Session ManagementProperties.’’To delete properties previously set by the client, useSmcDeleteProperties.__│ void SmcDeleteProperties(smc_conn, num_props, prop_names)SmcConn smc_conn;int num_props;char **prop_names;smc_conn The session management connection object.num_props The number of properties.prop_namesThe list of properties to delete.│__To get properties previously stored by the client, useSmcGetProperties.__│ Status SmcGetProperties(smc_conn, prop_reply_proc, client_data)SmcConn smc_conn;SmcPropReplyProc prop_reply_proc;SmPointer client_data;smc_conn The session management connection object.prop_reply_procThe callback to be invoked when the propertiesreply comes back.client_dataThis pointer to client data will be passed to theSmcPropReplyProc callback.│__The return value of SmcGetProperties is zero for failure anda positive value for success.Note that the library does not block until the propertiesreply comes back. Rather, a callback of typeSmcPropReplyProc is invoked when the data is ready.__│ typedef void (*SmcPropReplyProc)();void PropReplyProc(smc_conn, client_data, num_props, props)SmcConn smc_conn;SmPointer client_data;int num_props;SmProp **props;smc_conn The session management connection object.client_dataClient data specified when the callback wasregistered.num_props The number of properties returned.props The list of properties returned.│__To free each property, use SmFreeProperty (see section 8,‘‘Freeing Data’’). To free the actual array of pointers,use free.5.5. Interacting With the UserAfter receiving a ‘‘Save Yourself’’ message with aninteract_style of SmInteractStyleErrors orSmInteractStyleAny, the client may choose to interact withthe user. Because only one client can interact with theuser at a time, the client must call SmcInteractRequest andwait for an ‘‘Interact’’ message from the session manager.__│ Status SmcInteractRequest(smc_conn, dialog_type, interact_proc, client_data)SmcConn smc_conn;int dialog_type;SmcInteractProc interact_proc;SmPointer client_data;smc_conn The session management connection object.dialog_typeThe type of dialog the client wishes to present tothe user.interact_procThe callback to be invoked when the ‘‘Interact’’message arrives from the session manager.client_dataThis pointer to client data will be passed to theSmcInteractProc callback when the ‘‘Interact’’message arrives.│__The return value of SmcInteractRequest is zero for failureand a positive value for success.The dialog_type argument specifies either SmDialogError,indicating that the client wants to start an error dialog,or SmDialogNormal, meaning that the client wishes to start anonerror dialog.Note that if a shutdown is in progress, the user may havethe option of cancelling the shutdown. If the shutdown iscancelled, the clients that have not interacted yet with theuser will receive a ‘‘Shutdown Cancelled’’ message insteadof the ‘‘Interact’’ message.The SmcInteractProc callback will be invoked when the‘‘Interact’’ message arrives from the session manager.__│ typedef void (*SmcInteractProc)();void InteractProc(smc_conn, client_data)SmcConn smc_conn;SmPointer client_data;smc_conn The session management connection object.client_dataClient data specified when the callback wasregistered.│__After interacting with the user (in response to an‘‘Interact’’ message), you should call SmcInteractDone.__│ void SmcInteractDone(smc_conn, cancel_shutdown)SmcConn smc_conn;Bool cancel_shutdown;smc_conn The session management connection object.cancel_shutdownIf True, indicates that the user requests that theentire shutdown be cancelled.│__The cancel_shutdown argument may only be True if thecorresponding ‘‘Save Yourself’’ specified True for shutdownand SmInteractStyleErrors or SmInteractStyleAny for theinteract_style.5.6. Requesting a Save YourselfTo request a checkpoint from the session manager, useSmcRequestSaveYourself.__│ void SmcRequestSaveYourself(smc_conn, save_type, shutdown, interact_style, fast, global)SmcConn smc_conn;int save_type;Bool shutdown;int interact_style;Bool fast;Bool global;smc_conn The session management connection object.save_type Specifies the type of information that should besaved.shutdown Specifies if a shutdown is taking place.interact_styleThe type of interaction allowed with the user.fast If True, the client should save its state asquickly as possible.global Controls who gets the ‘‘Save Yourself.’’│__The save_type, shutdown, interact_style, and fast argumentsare discussed in more detail in section 5.1.1, ‘‘The SaveYourself Callback.’’If global is set to True, then the resulting ‘‘SaveYourself’’ should be sent to all clients in the session.For example, a vendor of a Uninterruptible Power Supply(UPS) might include a Session Management client that wouldmonitor the status of the UPS and generate a fast shutdownif the power is about to be lost.If global is set to False, then the ‘‘Save Yourself’’ shouldonly be sent to the client that requested it.5.7. Requesting a Save Yourself Phase 2In response to a ‘‘Save Yourself, the client may request tobe informed when all the other clients are quiescent so thatit can save their state. To do so, useSmcRequestSaveYourselfPhase2.__│ Status SmcRequestSaveYourselfPhase2(smc_conn, save_yourself_phase2_proc, client_data)SmcConn smc_conn;SmcSaveYourselfPhase2Proc save_yourself_phase2_proc;SmPointer client_data;smc_conn The session management connection object.save_yourself_phase2_procThe callback to be invoked when the ‘‘SaveYourself Phase 2’’ message arrives from thesession manager.client_dataThis pointer to client data will be passed to theSmcSaveYourselfPhase2Proc callback when the ‘‘SaveYourself Phase 2’’ message arrives.│__The return value of SmcRequestSaveYourselfPhase2 is zero forfailure and a positive value for success.This request is needed by clients that manage other clients(for example, window managers, workspace managers, and soon). The manager must make sure that all of the clientsthat are being managed are in an idle state so that theirstate can be saved.5.8. Completing a Save YourselfAfter saving state in response to a ‘‘Save Yourself’’message, you should call SmcSaveYourselfDone.__│ void SmcSaveYourselfDone(smc_conn, success)SmcConn smc_conn;Bool success;smc_conn The session management connection object.success If True, the ‘‘Save Yourself’’ operation wascompleted successfully.│__Before calling SmcSaveYourselfDone, the client must have seteach required property at least once since the clientregistered with the session manager.5.9. Using Smc Informational Functions__│ int SmcProtocolVersion(smc_conn)SmcConn smc_conn;│__SmcProtocolVersion returns the major version of the sessionmanagement protocol associated with this session.__│ int SmcProtocolRevision(smc_conn)SmcConn smc_conn;│__SmcProtocolRevision returns the minor version of the sessionmanagement protocol associated with this session.__│ char *SmcVendor(smc_conn)SmcConn smc_conn;│__SmcVendor returns a string that provides some identificationof the owner of the session manager. The string should befreed with a call to free.__│ char *SmcRelease(smc_conn)SmcConn smc_conn;│__SmcRelease returns a string that provides the release numberof the session manager. The string should be freed with acall to free.__│ char *SmcClientID(smc_conn)SmcConn smc_conn;│__SmcClientID returns a null-terminated string for the clientID associated with this connection. This information wasalso returned in SmcOpenConnection (it is provided here forconvenience). Call free on this pointer when the client IDis no longer needed.__│ IceConn SmcGetIceConnection(smc_conn)SmcConn smc_conn;│__SmcGetIceConnection returns the ICE connection objectassociated with this session management connection object.The ICE connection object can be used to get some additionalinformation about the connection. Some of the more usefulfunctions which can be used on the IceConn areIceConnectionNumber, IceConnectionString,IceLastSentSequenceNumber, IceLastReceivedSequenceNumber,and IcePing. For further information, see the Inter-ClientExchange Library standard.5.10. Error HandlingIf the client receives an unexpected protocol error from thesession manager, an error handler is invoked by SMlib. Adefault error handler exists that simply prints the errormessage to stderr and exits if the severity of the error isfatal. The client can change this error handler by callingthe SmcSetErrorHandler function.__│ SmcErrorHandler SmcSetErrorHandler(handler)SmcErrorHandler handler;handler The error handler. You should pass NULL torestore the default handler.│__SmcSetErrorHandler returns the previous error handler.The SmcErrorHandler has the following type:__│ typedef void (*SmcErrorHandler)();void ErrorHandler(smc_conn, swap, offending_minor_opcode, offending_sequence_num, error_class, severity, values)SmcConn smc_conn;Bool swap;int offending_minor_opcode;unsigned long offending_sequence_num;int error_class;int severity;IcePointer values;smc_conn The session management connection object.swap A flag that indicates if the specified values needbyte swapping.offending_minor_opcodeThe minor opcode of the offending message.offending_sequence_numThe sequence number of the offending message.error_classThe error class of the offending message.severity IceCanContinue, IceFatalToProtocol, orIceFatalToConnection.values Any additional error values specific to the minoropcode and class.│__Note that this error handler is invoked for protocol relatederrors. To install an error handler to be invoked when anIO error occurs, use IceSetIOErrorHandler. For furtherinformation, see the Inter-Client Exchange Library standard.6. Session Management Server (Sms) FunctionsThis section discusses how Session Management servers:• Initialize the library• Register the client• Send a ‘‘Save Yourself’’ message• Send a ‘‘Save Yourself Phase 2’’ message• Send an ‘‘Interact’’ message• Send a ‘‘Save Complete’’ message• Send a ‘‘Die’’ message• Cancel a shutdown• Return properties• Ping a client• Clean up after a client disconnects• Use Sms informational functions• Handle errors6.1. Initializing the LibrarySmsInitialize is the first SMlib function that should becalled by a session manager. It provides information aboutthe session manager and registers a callback that will beinvoked each time a new client connects to the sessionmanager.__│ Status SmsInitialize(vendor, release, new_client_proc, manager_data, host_based_auth_proc,error_length, error_string_ret)char *vendor;char *release;SmsNewClientProc new_client_proc;SmPointer manager_data;IceHostBasedAuthProc host_based_auth_proc;int error_length;char *error_string_ret;vendor A string specifying the session manager vendor.release A string specifying the session manager releasenumber.new_client_procCallback to be invoked each time a new clientconnects to the session manager.manager_dataWhen the SmsNewClientProc callback is invoked,this pointer to manager data will be passed.host_based_auth_procHost based authentication callback.error_lengthLength of the error_string_ret argument passed in.error_string_retReturns a null-terminated error message, if any.The error_string_ret points to user suppliedmemory. No more than error_length bytes are used.│__After the SmsInitialize function is called, the sessionmanager should call the IceListenForConnections function tolisten for new connections. Afterwards, each time a clientconnects, the session manager should callIceAcceptConnection.See section 9, ‘‘Authentication of Clients,’’ for moredetails on authentication (including host basedauthentication). Also see the Inter-Client Exchange Librarystandard for further details on listening for and acceptingICE connections.Each time a new client connects to the session manager, theSmsNewClientProc callback is invoked. The session managerobtains a new opaque connection object that it should usefor all future interaction with the client. At this time,the session manager must also register a set of callbacks torespond to the different messages that the client mightsend.__│ typedef Status (*SmsNewClientProc)();Status NewClientProc(sms_conn, manager_data, mask_ret, callbacks_ret, failure_reason_ret)SmsConn sms_conn;SmPointer manager_data;unsigned long *mask_ret;SmsCallbacks *callbacks_ret;char **failure_reason_ret;sms_conn A new opaque connection object.manager_dataManager data specified when the callback wasregistered.mask_ret On return, indicates which callbacks were set bythe session manager.callbacks_retOn return, contains the callbacks registered bythe session manager.failure_reason_retFailure reason returned.│__If a failure occurs, the SmsNewClientProc should return azero status as well as allocate and return a failure reasonstring in failure_reason_ret. SMlib will be responsible forfreeing this memory.The session manager must register a set of callbacks torespond to client events. The mask_ret argument specifieswhich callbacks are set. All of the callbacks specified inthis version of SMlib are mandatory. The mask_ret argumentis necessary in order to maintain backwards compatibility infuture versions of the library.The following values may be ORed together to obtain a maskvalue:SmsRegisterClientProcMaskSmsInteractRequestProcMaskSmsInteractDoneProcMaskSmsSaveYourselfRequestProcMaskSmsSaveYourselfP2RequestProcMaskSmsSaveYourselfDoneProcMaskSmsCloseConnectionProcMaskSmsSetPropertiesProcMaskSmsDeletePropertiesProcMaskSmsGetPropertiesProcMaskFor each callback, the session manager can register apointer to manager data specific to that callback. Thispointer will be passed to the callback when it is invoked bySMlib.__│ typedef struct {struct {SmsRegisterClientProc callback;SmPointer manager_data;} register_client;struct {SmsInteractRequestProc callback;SmPointer manager_data;} interact_request;struct {SmsInteractDoneProc callback;SmPointer manager_data;} interact_done;struct {SmsSaveYourselfRequestProc callback;SmPointer manager_data;} save_yourself_request;struct {SmsSaveYourselfPhase2RequestProc callback;SmPointer manager_data;} save_yourself_phase2_request;struct {SmsSaveYourselfDoneProc callback;SmPointer manager_data;} save_yourself_done;struct {SmsCloseConnectionProc callback;SmPointer manager_data;} close_connection;struct {SmsSetPropertiesProc callback;SmPointer manager_data;} set_properties;struct {SmsDeletePropertiesProc callback;SmPointer manager_data;} delete_properties;struct {SmsGetPropertiesProc callback;SmPointer manager_data;} get_properties;} SmsCallbacks;│__6.1.1. The Register Client CallbackThe Register Client callback is the first callback that willbe invoked after the client connects to the session manager.Its type is SmsRegisterClientProc.__│ typedef Status (*SmsRegisterClientProc();Status RegisterClientProc(sms_conn, manager_data, previous_id)SmsConn sms_conn;SmPointer manager_data;char *previous_id;sms_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.previous_idThe client ID from the previous session.│__Before any further interaction takes place with the client,the client must be registered with the session manager.If the client is being restarted from a previous session,previous_id will contain a null-terminated stringrepresenting the client ID from the previous session. Callfree on the previous_id pointer when it is no longer needed.If the client is first joining the session, previous_id willbe NULL.If previous_id is invalid, the session manager should notregister the client at this time. This callback shouldreturn a status of zero, which will cause an error messageto be sent to the client. The client should re-registerwith previous_id set to NULL.Otherwise, the session manager should register the clientwith a unique client ID by calling theSmsRegisterClientReply function (to be discussed shortly),and the SmsRegisterClientProc callback should return astatus of one.6.1.2. The Interact Request CallbackThe Interact Request callback is of typeSmsInteractRequestProc.__│ typedef void (*SmsInteractRequestProc)();void InteractRequestProc(sms_conn, manager_data, dialog_type)SmsConn sms_conn;SmPointer manager_data;int dialog_type;sms_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.dialog_typeThe type of dialog the client wishes to present tothe user.│__When a client receives a ‘‘Save Yourself’’ message with aninteract_style of SmInteractStyleErrors orSmInteractStyleAny, the client may choose to interact withthe user. Because only one client can interact with theuser at a time, the client must request to interact with theuser. The session manager should keep a queue of allclients wishing to interact. It should send an ‘‘Interact’’message to one client at a time and wait for an ‘‘InteractDone’’ message before continuing with the next client.The dialog_type argument specifies either SmDialogError,indicating that the client wants to start an error dialog,or SmDialogNormal, meaning that the client wishes to start anonerror dialog.If a shutdown is in progress, the user may have the optionof cancelling the shutdown. If the shutdown is cancelled(specified in the ‘‘Interact Done’’ message), the sessionmanager should send a ‘‘Shutdown Cancelled’’ message to eachclient that requested to interact.6.1.3. The Interact Done CallbackWhen the client is done interacting with the user, theSmsInteractDoneProc callback will be invoked.__│ typedef void (*SmsInteractDoneProc)();void InteractDoneProc(sms_conn, manager_data, cancel_shutdown)SmsConn sms_conn;SmPointer manager_data;Bool cancel_shutdown;sms_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.cancel_shutdownSpecifies if the user requests that the entireshutdown be cancelled.│__Note that the shutdown can be cancelled only if thecorresponding ‘‘Save Yourself’’ specified True for shutdownand SmInteractStyleErrors or SmInteractStyleAny for theinteract_style.6.1.4. The Save Yourself Request CallbackThe Save Yourself Request callback is of typeSmsSaveYourselfRequestProc.__│ typedef void (*SmsSaveYourselfRequestProc)();void SaveYourselfRequestProc(sms_conn, manager_data, save_type, shutdown, interact_style, fast, global)SmsConn sms_conn;SmPointer manager_data;int save_type;Bool shutdown;int interact_style;Bool fast;Bool global;sms_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.save_type Specifies the type of information that should besaved.shutdown Specifies if a shutdown is taking place.interact_styleThe type of interaction allowed with the user.fast If True, the client should save its state asquickly as possible.global Controls who gets the ‘‘Save Yourself.’’│__The Save Yourself Request prompts the session manager toinitiate a checkpoint or shutdown. For information on thesave_type, shutdown, interact_style, and fast arguments, seesection 6.3, ‘‘Sending a Save Yourself Message.’’If global is set to True, then the resulting ‘‘SaveYourself’’ should be sent to all applications. If global isset to False, then the ‘‘Save Yourself’’ should only be sentto the client that requested it.6.1.5. The Save Yourself Phase 2 Request CallbackThe Save Yourself Phase 2 Request callback is of typeSmsSaveYourselfPhase2RequestProc.__│ typedef void (*SmsSaveYourselfPhase2RequestProc)();void SmsSaveYourselfPhase2RequestProc(sms_conn, manager_data)SmsConn sms_conn;SmPointer manager_data;sms_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.│__This request is sent by clients that manage other clients(for example, window managers, workspace managers, and soon). Such managers must make sure that all of the clientsthat are being managed are in an idle state so that theirstate can be saved.6.1.6. The Save Yourself Done CallbackWhen the client is done saving its state in response to a‘‘Save Yourself’’ message, the SmsSaveYourselfDoneProc willbe invoked.__│ typedef void (*SmsSaveYourselfDoneProc)();void SaveYourselfDoneProc(sms_conn, manager_data, success)SmsConn sms_conn;SmPointer manager_data;Bool success;sms_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.success If True, the Save Yourself operation was completedsuccessfully.│__Before the ‘‘Save Yourself Done’’ was sent, the client musthave set each required property at least once since itregistered with the session manager.6.1.7. The Connection Closed CallbackIf the client properly terminates (that is, it callsSmcCloseConnection), the SmsCloseConnectionProc callback isinvoked.__│ typedef void (*SmsCloseConnectionProc)();void CloseConnectionProc(sms_conn, manager_data, count, reason_msgs)SmsConn sms_conn;SmPointer manager_data;int count;char **reason_msgs;sms_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.count The number of reason messages.reason_msgsThe reasons for closing the connection.│__The reason_msgs argument will most likely be NULL and thecount argument zero (0) if resignation is expected by theuser. Otherwise, it contains a list of null-terminatedCompound Text strings representing the reason fortermination. The session manager should display thesereason messages to the user.Call SmFreeReasons to free the reason messages. For furtherinformation, see section 8, ‘‘Freeing Data.’’6.1.8. The Set Properties CallbackWhen the client sets session management properties, theSmsSetPropertiesProc callback will be invoked.__│ typedef void (*SmsSetPropertiesProc)();void SetPropertiesProc(sms_conn, manager_data, num_props, props)SmsConn sms_conn;SmPointer manager_data;int num_props;SmProp **props;smc_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.num_props The number of properties.props The list of properties to set.│__The properties are specified as an array of propertypointers. For a description of session managementproperties and the SmProp structure, see section 7,‘‘Session Management Properties.’’Previously set property values may be over-written. Someproperties have predefined semantics. The session manageris required to store nonpredefined properties.To free each property, use SmFreeProperty. For furtherinformation, see section 8, ‘‘Freeing Data.’’ You shouldfree the actual array of pointers with a call to free.6.1.9. The Delete Properties CallbackWhen the client deletes session management properties, theSmsDeletePropertiesProc callback will be invoked.__│ typedef void (*SmsDeletePropertiesProc)();void DeletePropertiesProc(sms_conn, manager_data, num_props, prop_names)SmsConn sms_conn;SmPointer manager_data;int num_props;char **prop_names;smc_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.num_props The number of properties.prop_namesThe list of properties to delete.│__The properties are specified as an array of strings. For adescription of session management properties and the SmPropstructure, see section 7, ‘‘Session Management Properties.’’6.1.10. The Get Properties CallbackThe SmsGetPropertiesProc callback is invoked when the clientwants to retrieve properties it set.__│ typedef void (*SmsGetPropertiesProc)();void GetPropertiesProc(sms_conn, manager_data)SmsConn sms_conn;SmPointer manager_data;smc_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.│__The session manager should respond by callingSmsReturnProperties. All of the properties set for thisclient should be returned.6.2. Registering the ClientTo register a client (in response to a SmsRegisterClientProccallback), use SmsRegisterClientReply.__│ Status SmsRegisterClientReply(sms_conn, client_id)SmsConn sms_conn;char *client_id;sms_conn The session management connection object.client_id A null-terminated string representing a uniqueclient ID.│__The return value of SmsRegisterClientReply is zero forfailure and a positive value for success. Failure willoccur if SMlib can not allocate memory to hold a copy of theclient ID for it’s own internal needs.If a non-NULL previous_id was specified when the clientregistered itself, client_id should be identical toprevious_id.Otherwise, client_id should be a unique ID freshly generatedby the session manager. In addition, the session managershould send a ‘‘Save Yourself’’ message with type = Local,shutdown = False, interact-style = None, and fast = Falseimmediately after registering the client.Note that once a client ID has been assigned to the client,the client keeps this ID indefinitely. If the client isterminated and restarted, it will be reassigned the same ID.It is desirable to be able to pass client IDs around frommachine to machine, from user to user, and from sessionmanager to session manager, while retaining the identity ofthe client. This, combined with the indefinite persistenceof client IDs, means that client IDs need to be globallyunique.You should call the SmsGenerateClientID function to generatea globally unique client ID.__│ char *SmsGenerateClientID(sms_conn)SmsConn sms_conn;sms_conn The session management connection object.│__NULL will be returned if the ID could not be generated.Otherwise, the return value of the function is the clientID. It should be freed with a call to free when no longerneeded.6.3. Sending a Save Yourself MessageTo send a ‘‘Save Yourself’’ to a client, useSmsSaveYourself.__│ void SmsSaveYourself(sms_conn, save_type, shutdown, interact_style, fast)SmsConn sms_conn;int save_type;Bool shutdown;int interact_style;Bool fast;sms_conn The session management connection object.save_type Specifies the type of information that should besaved.shutdown Specifies if a shutdown is taking place.interact_styleThe type of interaction allowed with the user.fast If True, the client should save its state asquickly as possible.│__The session manager sends a ‘‘Save Yourself’’ message to aclient either to checkpoint it or just before termination sothat it can save its state. The client responds with zeroor more ‘‘Set Properties’’ messages to update the propertiesindicating how to restart the client. When all theproperties have been set, the client sends a ‘‘Save YourselfDone’’ message.If interact_style is SmInteractStyleNone, the client mustnot interact with the user while saving state. Ifinteract_style is SmInteractStyleErrors, the client mayinteract with the user only if an error condition arises.If interact_style is SmInteractStyleAny, then the client mayinteract with the user for any purpose. The client mustsend an ‘‘Interact Request’’ message and wait for an‘‘Interact’’ message from the session manager before it caninteract with the user. When the client is done interactingwith the user, it should send an ‘‘Interact Done’’ message.The ‘‘Interact Request’’ message can be sent any time aftera ‘‘Save Yourself’’ and before a ‘‘Save Yourself Done.’’If save_type is SmSaveLocal, the client must update theproperties to reflect its current state. Specifically, itshould save enough information to restore the state as seenby the user of this client. It should not affect the stateas seen by other users. If save_type is SmSaveGlobal theuser wants the client to commit all of its data topermanent, globally accessible storage. If save_type isSmSaveBoth, the client should do both of these (it shouldfirst commit the data to permanent storage before updatingits properties).The shutdown argument specifies whether the session is beingshut down. The interaction is different depending onwhether or not shutdown is set. If not shutting down, thenthe client can save and resume normal operation. Ifshutting down, the client must save and then must preventinteraction until it receives either a ‘‘Die’’ or a‘‘Shutdown Cancelled,’’ because anything the user does afterthe save will be lost.The fast argument specifies that the client should save itsstate as quickly as possible. For example, if the sessionmanager knows that power is about to fail, it should setfast to True.6.4. Sending a Save Yourself Phase 2 MessageIn order to send a ‘‘Save Yourself Phase 2’’ message to aclient, use SmsSaveYourselfPhase2.__│ void SmsSaveYourselfPhase2(sms_conn)SmsConn sms_conn;sms_conn The session management connection object.│__The session manager sends this message to a client that haspreviously sent a ‘‘Save Yourself Phase 2 Request’’ message.This message informs the client that all other clients arein a fixed state and this client can save state that isassociated with other clients.6.5. Sending an Interact MessageTo send an ‘‘Interact’’ message to a client, useSmsInteract.__│ void SmsInteract(sms_conn)SmsConn sms_conn;sms_conn The session management connection object.│__The ‘‘Interact’’ message grants the client the privilege ofinteracting with the user. When the client is doneinteracting with the user, it must send an ‘‘Interact Done’’message to the session manager.6.6. Sending a Save Complete MessageTo send a ‘‘Save Complete’’ message to a client, useSmsSaveComplete.__│ void SmsSaveComplete(sms_conn)SmsConn sms_conn;sms_conn The session management connection object.│__The session manager sends this message when it is done witha checkpoint. The client is then free to change its state.6.7. Sending a Die MessageTo send a ‘‘Die’’ message to a client, use SmsDie.__│ void SmsDie(sms_conn)SmsConn sms_conn;sms_conn The session management connection object.│__Before the session manager terminates, it should wait for a‘‘Connection Closed’’ message from each client that it senta ‘‘Die’’ message to, timing out appropriately.6.8. Cancelling a ShutdownTo cancel a shutdown, use SmsShutdownCancelled.__│ void SmsShutdownCancelled(sms_conn)SmsConn sms_conn;sms_conn The session management connection object.│__The client can now continue as if the shutdown had neverhappened. If the client has not sent a ‘‘Save YourselfDone’’ message yet, it can either abort the save and send a‘‘Save Yourself Done’’ with the success argument set toFalse, or it can continue with the save and send a ‘‘SaveYourself Done’’ with the success argument set to reflect theoutcome of the save.6.9. Returning PropertiesIn response to a ‘‘Get Properties’’ message, the sessionmanager should call SmsReturnProperties.__│ void SmsReturnProperties(sms_conn, num_props, props)SmsConn sms_conn;int num_props;SmProp **props;sms_conn The session management connection object.num_props The number of properties.props The list of properties to return to the client.│__The properties are returned as an array of propertypointers. For a description of session managementproperties and the SmProp structure, see section 7,‘‘Session Management Properties.’’6.10. Pinging a ClientTo check that a client is still alive, you should use theIcePing function provided by the ICE library. To do so, theICE connection must be obtained using theSmsGetIceConnection (see section 6.12, ‘‘Using SmsInformational Functions’’).__│ void IcePing(ice_conn, ping_reply_proc, client_data)IceConn ice_conn;IcePingReplyProc ping_reply_proc;IcePointer client_data;ice_conn A valid ICE connection object.ping_reply_procThe callback to invoke when the Ping replyarrives.client_dataThis pointer will be passed to theIcePingReplyProc callback.│__When the Ping reply is ready (if ever), the IcePingReplyProccallback will be invoked. A session manager should havesome sort of timeout period, after which it assumes theclient has unexpectedly died.__│ typedef void (*IcePingReplyProc)();void PingReplyProc(ice_conn, client_data)IceConn ice_conn;IcePointer client_data;ice_conn The ICE connection object.client_dataThe client data specified in the call to IcePing.│__6.11. Cleaning Up After a Client DisconnectsWhen the session manager receives a ‘‘Connection Closed’’message or otherwise detects that the client aborted theconnection, it should call the SmsCleanUp function in orderto free up the connection object.__│ void SmsCleanUp(sms_conn)SmsConn sms_conn;sms_conn The session management connection object.│__6.12. Using Sms Informational Functions__│ int SmsProtocolVersion(sms_conn)SmsConn sms_conn;│__SmsProtocolVersion returns the major version of the sessionmanagement protocol associated with this session.__│ int SmsProtocolRevision(sms_conn)SmsConn sms_conn;│__SmsProtocolRevision returns the minor version of the sessionmanagement protocol associated with this session.__│ char *SmsClientID(sms_conn)SmsConn sms_conn;│__SmsClientID returns a null-terminated string for the clientID associated with this connection. You should call free onthis pointer when the client ID is no longer needed.To obtain the host name of a client, use SmsClientHostName.This host name will be needed to restart the client.__│ char *SmsClientHostName(sms_conn)SmsConn sms_conn;│__The string returned is of the form protocol/hostname, whereprotocol is one of {tcp, decnet, local}. You should callfree on the string returned when it is no longer needed.__│ IceConn SmsGetIceConnection(sms_conn)SmsConn sms_conn;│__SmsGetIceConnection returns the ICE connection objectassociated with this session management connection object.The ICE connection object can be used to get some additionalinformation about the connection. Some of the more usefulfunctions which can be used on the IceConn areIceConnectionNumber, and IceLastSequenceNumber. For furtherinformation, see the Inter-Client Exchange Library standard.6.13. Error HandlingIf the session manager receives an unexpected protocol errorfrom a client, an error handler is invoked by SMlib. Adefault error handler exists which simply prints the errormessage (it does not exit). The session manager can changethis error handler by calling SmsSetErrorHandler.__│ SmsErrorHandler SmsSetErrorHandler(handler)SmsErrorHandler handler;handler The error handler. You should pass NULL torestore the default handler.│__SmsSetErrorHandler returns the previous error handler. TheSmsErrorHandler has the following type:__│ typedef void (*SmsErrorHandler)();void ErrorHandler(sms_conn, swap, offending_minor_opcode, offending_sequence_num, error_class, severity, values)SmsConn sms_conn;Bool swap;int offending_minor_opcode;unsigned long offending_sequence_num;int error_class;int severity;IcePointer values;sms_conn The session management connection object.swap A flag which indicates if the specified valuesneed byte swapping.offending_minor_opcodeThe minor opcode of the offending message.offending_sequence_numThe sequence number of the offending message.error_classThe error class of the offending message.severity IceCanContinue, IceFatalToProtocol, orIceFatalToConnection.values Any additional error values specific to the minoropcode and class.│__Note that this error handler is invoked for protocol relatederrors. To install an error handler to be invoked when anIO error occurs, use IceSetIOErrorHandler. For furtherinformation, see the Inter-Client Exchange Library standard.7. Session Management PropertiesEach property is defined by the SmProc structure:typedef struct {char *name; /* name of property */char *type; /* type of property */int num_vals; /* number of values */SmPropValue *vals; /* the list of values */} SmProp;typedef struct {int length; /* the length of the value */SmPointer value; /* the value */} SmPropValue;The X Session Management Protocol defines a list ofpredefined properties, several of which are required to beset by the client. The following table specifies thepredefined properties and indicates which ones are required.Each property has a type associated with it.A type of SmCARD8 indicates that there is a single 1-bytevalue. A type of SmARRAY8 indicates that there is a singlearray of bytes. A type of SmLISTofARRAY8 indicates thatthere is a list of array of bytes.* Required if any state is stored in an external repository(for example, state file).• SmCloneCommandThis is like the SmRestartCommand, except it restarts acopy of the application. The only difference is thatthe application does not supply its client ID atregister time. On POSIX systems, this should be oftype SmLISTofARRAY8.• SmCurrentDirectoryOn POSIX-based systems, this specifies the value of thecurrent directory that needs to be set up prior tostarting the SmProgram and should of type SmARRAY8.• SmDiscardCommandThe discard command contains a command that whendelivered to the host that the client is running on(determined from the connection), will cause it todiscard any information about the current state. Ifthis command is not specified, the Session Manager willassume that all of the client’s state is encoded in theSmRestartCommand. On POSIX systems, the type should beSmLISTofARRAY8.• SmEnvironmentOn POSIX based systems, this will be of typeSmLISTofARRAY8, where the ARRAY8s alternate betweenenvironment variable name and environment variablevalue.• SmProcessIDThis specifies an OS-specific identifier for theprocess. On POSIX systems, this should contain thereturn value of getpid turned into a Latin-1 (decimal)string.• SmProgramThis is the name of the program that is running. OnPOSIX systems, this should be first parameter passed toexecve and should be of type SmARRAY8.• SmRestartCommandThe restart command contains a command that, whendelivered to the host that the client is running on(determined from the connection), will cause the clientto restart in its current state. On POSIX-basedsystems, this is of type SmLISTofARRAY8, and each ofthe elements in the array represents an element in theargv array. This restart command should ensure thatthe client restarts with the specified client-ID.• SmResignCommandA client that sets the SmRestartStyleHint toSmRestartAnway uses this property to specify a commandthat undoes the effect of the client and removes anysaved state. As an example, consider a user that runsxmodmap, which registers with the Session Manager, setsSmRestartStyleHint to SmRestartAnyway, and thenterminates. To allow the Session Manager (at theuser’s request) to undo this, xmodmap would register aSmResignCommand that undoes the effects of the xmodmap.• SmRestartStyleHintIf the RestartStyleHint property is present, it willcontain the style of restarting the client prefers. Ifthis style is not specified, SmRestartIfRunning isassumed. The possible values are as follows:The SmRestartIfRunning style is used in the usual case.The client should be restarted in the next session ifit was running at the end of the current session.The SmRestartAnyway style is used to tell the SessionManager that the application should be restarted in thenext session even if it exits before the currentsession is terminated. It should be noted that this isonly a hint and the Session Manager will follow thepolicies specified by its users in determining whatapplications to restart.A client that uses SmRestartAnyway should also set theSmResignCommand and SmShutdownCommand properties tocommands that undo the state of the client after itexits.The SmRestartImmediately style is like SmRestartAnyway,but, in addition, the client is meant to runcontinuously. If the client exits, the Session Managershould try to restart it in the current session.SmRestartNever style specifies that the client does notwish to be restarted in the next session.• SmShutdownCommandThis command is executed at shutdown time to clean upafter a client that is no longer running but retainedits state by setting SmRestartStyleHint toSmRestartAnyway. The client must not remove any savedstate as the client is still part of the session. Asan example, consider a client that turns on a camera atstart up time. This client then exits. At sessionshutdown, the user wants the camera turned off. Thisclient would set the SmRestartStyleHint toSmRestartAnyway and would register a SmShutdownCommandthat would turn off the camera.• SmUserIDSpecifies the user ID. On POSIX-based systems, thiswill contain the user’s name (the pw_name member ofstruct passwd).8. Freeing DataTo free an individual property, use SmFreeProperty.__│ void SmFreeProperty(prop)SmProp *prop;prop The property to free.│__To free the reason strings from the SmsCloseConnectionProccallback, use SmFreeReasons.__│ void SmFreeReasons(count, reasons)int count;char **reasons;count The number of reason strings.reasons The list of reason strings to free.│__9. Authentication of ClientsAs stated earlier, the session management protocol islayered on top of ICE. Authentication occurs at two levelsin the ICE protocol:• The first is when an ICE connection is opened.• The second is when a Protocol Setup occurs on an ICEconnection.The authentication methods that are available areimplementation-dependent (that is., dependent on the ICEliband SMlib implementations in use). For further information,see the Inter-Client Exchange Library standard.10. Working in a Multi-Threaded EnvironmentTo declare that multiple threads in an application will beusing SMlib (or any other library layered on top of ICElib),you should call IceInitThreads. For further information,see the Inter-Client Exchange Library standard.11. AcknowledgementsThanks to the following people for their participation inthe X Session Management design: Jordan Brown, Ellis Cohen,Donna Converse, Stephen Gildea, Vania Joloboff, StuartMarks, Bob Scheifler, Ralph Swick, and Mike Wexler.− 1 −

Ralph Mor
X Consortium

Copyright © 1993, 1994 X Consortium

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘‘Software’’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘‘AS IS’’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of the X Consortium shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from the X Consortium.

X Window System is a trademark of X Consortium, Inc.

1. Overview of Session ManagementThe purpose of the X Session Management Protocol (XSMP) isto provide a uniform mechanism for users to save and restoretheir sessions. A session is a group of clients, each ofwhich has a particular state. The session is controlled bya network service called the session manager. The sessionmanager issues commands to its clients on behalf of theuser. These commands may cause clients to save their stateor to terminate. It is expected that the client will saveits state in such a way that the client can be restarted ata later time and resume its operation as if it had neverbeen terminated. A client’s state might include informationabout the file currently being edited, the current positionof the insertion point within the file, or the start of anuncommitted transaction. The means by which clients arerestarted is unspecified by this protocol.For purposes of this protocol, a client of the sessionmanager is defined as a connection to the session manager.A client is typically, though not necessarily, a processrunning an application program connected to an X display.However, a client may be connected to more than one Xdisplay or not be connected to any X displays at all.2. The Session Management LibraryThe Session Management Library (SMlib) is a low-level "C"language interface to XSMP. It is expected that higherlevel toolkits, such as Xt, will hide many of the details ofsession management from clients. Higher level toolkitsmight also be developed for session managers to use, but nosuch effort is currently under way.SMlib has two parts to it:• One set of functions for clients that want to be partof a session• One set of functions for session managers to callSome applications will use both sets of functions and act asnested session managers. That is, they will be both asession manager and a client of another session. An exampleis a mail program that could start a text editor for editingthe text of a mail message. The mail program is part of aregular session and, at the same time, is also acting as asession manager to the editor.Clients initialize by connecting to the session manager andobtaining a client-ID that uniquely identifies them in thesession. The session manager maintains a list of propertiesfor each client in the session. These properties describethe client’s environment and, most importantly, describe howthe client can be restarted (via an SmRestartCommand).Clients are expected to save their state in such a way as toallow multiple instantiations of themselves to be managedindependently. For example, clients may use their client-IDas part of a filename in which to store the state for aparticular instantiation. The client-ID should be saved aspart of the SmRestartCommand so that the client will retainthe same ID after it is restarted.Once the client initializes itself with the session manager,it must be ready to respond to messages from the sessionmanager. For example, it might be asked to save its stateor to terminate. In the case of a shutdown, the sessionmanager might give each client a chance to interact with theuser and cancel the shutdown.3. Understanding SMlib’s Dependence on ICEThe X Session Management Protocol is layered on top of theInter-Client Exchange (ICE) Protocol. The ICE protocol isdesigned to multiplex several protocols over a singleconnection. As a result, working with SMlib requires alittle knowledge of how the ICE library works.The ICE library utilizes callbacks to process messages.When a client detects that there is data to read on an ICEconnection, it should call the IceProcessMessages function.IceProcessMessages will read the message header and look atthe major opcode in order to determine which protocol themessage was intended for. The appropriate protocol librarywill then be triggered to unpack the message and hand it offto the client via a callback.The main point to be aware of is that an application usingSMlib must have some code that detects when there is data toread on an ICE connection. This can be done via a selectcall on the file descriptor for the ICE connection, but moretypically, XtAppAddInput will be used to register a callbackthat will invoke IceProcessMessages each time there is datato read on the ICE connection.To further complicate things, knowing which file descriptorsto call select on requires an understanding of how ICEconnections are created. On the client side, a call must bemade to SmcOpenConnection in order to open a connection witha session manager. SmcOpenConnection will internally make acall into IceOpenConnection, which will, in turn, determineif an ICE connection already exists between the client andsession manager. Most likely, a connection will not alreadyexist and a new ICE connection will be created. The mainpoint to be aware of is that, on the client side, it is notobvious when ICE connections get created or destroyed,because connections are shared when possible. To deal withthis, the ICE library lets the application register watchprocedures that will be invoked each time an ICE connectionis opened or closed. These watch procedures could be usedto add or remove ICE file descriptors from the list ofdescriptors to call select on.On the session manager side, things work a bit differently.The session manager has complete control over the creationof ICE connections. The session manager has to first callIceListenForConnections in order to start listening forconnections from clients. Once a connection attempt isdetected, IceAcceptConnection must be called, and thesession manager can simply add the new ICE file descriptorto the list of descriptors to call select on.For further information on the library functions related toICE connections, see the Inter-Client Exchange Librarystandard.4. Header Files and Library NameApplications (both session managers and clients) shouldinclude the header file <X11/SM/SMlib.h>. This header filedefines all of the SMlib data structures and functionprototypes. SMlib.h includes the header file <X11/SM/SM.h>,which defines all of the SMlib constants.Because SMlib is dependent on ICE, applications should linkagainst SMlib and ICElib by using -lSM -lICE.5. Session Management Client (Smc) FunctionsThis section discusses how Session Management clients:• Connect to the Session Manager• Close the connection• Modify callbacks• Set, delete, and retrieve Session Manager properties• Interact with the user• Request a ‘‘Save Yourself’’• Request a ‘‘Save Yourself Phase 2’’• Complete a ‘‘Save Yourself’’• Use Smc informational functions• Handle Errors5.1. Connecting to the Session ManagerTo open a connection with a session manager, useSmcOpenConnection.__│ SmcConn SmcOpenConnection(network_ids_list, context, xsmp_major_rev, xsmp_minor_rev,mask, callbacks, previous_id, client_id_ret, error_length, error_string_ret)char *network_ids_list;SmPointer context;int xsmp_major_rev;int xsmp_minor_rev;unsigned long mask;SmcCallbacks *callbacks;char *previous_id;char **client_id_ret;int error_length;char *error_string_ret;network_ids_listSpecifies the network ID(s) of the sessionmanager.context A pointer to an opaque object or NULL. Used todetermine if an ICE connection can be shared (seebelow).xsmp_major_revThe highest major version of the XSMP theapplication supports.xsmp_minor_revThe highest minor version of the XSMP theapplication supports (for the specifiedxsmp_major_rev).mask A mask indicating which callbacks to register.callbacks The callbacks to register. These callbacks areused to respond to messages from the sessionmanager.previous_idThe client ID from the previous session.client_id_retThe client ID for the current session is returned.error_lengthLength of the error_string_ret argument passed in.error_string_retReturns a null-terminated error message, if any.The error_string_ret argument points to usersupplied memory. No more than error_length bytesare used.│__The network_ids_list argument is a null-terminated stringcontaining a list of network IDs for the session manager,separated by commas. If network_ids_list is NULL, the valueof the SESSION_MANAGER environment variable will be used.Each network ID has the following format:An attempt will be made to use the first network ID. Ifthat fails, an attempt will be made using the second networkID, and so on.After the connection is established, SmcOpenConnectionregisters the client with the session manager. If theclient is being restarted from a previous session,previous_id should contain a null terminated stringrepresenting the client ID from the previous session. Ifthe client is first joining the session, previous_id shouldbe set to NULL. If previous_id is specified but isdetermined to be invalid by the session manager, SMlib willre-register the client with previous_id set to NULL.If SmcOpenConnection succeeds, it returns an opaqueconnection pointer of type SmcConn and the client_id_retargument contains the client ID to be used for this session.The client_id_ret should be freed with a call to free whenno longer needed. On failure, SmcOpenConnection returnsNULL, and the reason for failure is returned inerror_string_ret.Note that SMlib uses the ICE protocol to establish aconnection with the session manager. If an ICE connectionalready exists between the client and session manager, itmight be possible for the same ICE connection to be used forsession management.The context argument indicates how willing the client is toshare the ICE connection with other protocols. If contextis NULL, then the caller is always willing to share theconnection. If context is not NULL, then the caller is notwilling to use a previously opened ICE connection that has adifferent non-NULL context associated with it.As previously discussed (section 3, ‘‘Understanding SMlib’sDependence on ICE’’), the client will have to keep track ofwhen ICE connections are created or destroyed (usingIceAddConnectionWatch and IceRemoveConnectionWatch), andwill have to call IceProcessMessages each time a selectshows that there is data to read on an ICE connection. Forfurther information, see the Inter-Client Exchange Librarystandard.The callbacks argument contains a set of callbacks used torespond to session manager events. The mask argumentspecifies which callbacks are set. All of the callbacksspecified in this version of SMlib are mandatory. The maskargument is necessary in order to maintain backwardscompatibility in future versions of the library.The following values may be ORed together to obtain a maskvalue:SmcSaveYourselfProcMaskSmcDieProcMaskSmcSaveCompleteProcMaskSmcShutdownCancelledProcMaskFor each callback, the client can register a pointer toclient data. When SMlib invokes the callback, it will passthe client data pointer.__│ typedef struct {struct {SmcSaveYourselfProc callback;SmPointer client_data;} save_yourself;struct {SmcDieProc callback;SmPointer client_data;} die;struct {SmcSaveCompleteProc callback;SmPointer client_data;} save_complete;struct {SmcShutdownCancelledProc callback;SmPointer client_data;} shutdown_cancelled;} SmcCallbacks;│__5.1.1. The Save Yourself CallbackThe Save Yourself callback is of type SmcSaveYourselfProc.__│ typedef void (*SmcSaveYourselfProc)();void SaveYourselfProc(smc_conn, client_data, save_type, shutdown, interact_style, fast)SmcConn smc_conn;SmPointer client_data;int save_type;Bool shutdown;int interact_style;Bool fast;smc_conn The session management connection object.client_dataClient data specified when the callback wasregistered.save_type Specifies the type of information that should besaved.shutdown Specifies if a shutdown is taking place.interact_styleThe type of interaction allowed with the user.fast If True, the client should save its state asquickly as possible.│__The session manager sends a ‘‘Save Yourself’’ message to aclient either to checkpoint it or just before termination sothat it can save its state. The client responds with zeroor more calls to SmcSetProperties to update the propertiesindicating how to restart the client. When all theproperties have been set, the client callsSmcSaveYourselfDone.If interact_style is SmInteractStyleNone, the client mustnot interact with the user while saving state. Ifinteract_style is SmInteractStyleErrors, the client mayinteract with the user only if an error condition arises.If interact_style is SmInteractStyleAny, then the client mayinteract with the user for any purpose. Because only oneclient can interact with the user at a time, the client mustcall SmcInteractRequest and wait for an ‘‘Interact’’ messagefrom the session manager. When the client is doneinteracting with the user, it calls SmcInteractDone. Theclient may only call SmcInteractRequest after it receives a‘‘Save Yourself’’ message and before it callsSmcSaveYourselfDone.If save_type is SmSaveLocal, the client must update theproperties to reflect its current state. Specifically, itshould save enough information to restore the state as seenby the user of this client. It should not affect the stateas seen by other users. If save_type is SmSaveGlobal, theuser wants the client to commit all of its data topermanent, globally accessible storage. If save_type isSmSaveBoth, the client should do both of these (it shouldfirst commit the data to permanent storage before updatingits properties).Some examples are as follows:• If a word processor were sent a ‘‘Save Yourself’’ witha type of SmSaveLocal, it could create a temporary filethat included the current contents of the file, thelocation of the cursor, and other aspects of thecurrent editing session. It would then update itsSmRestartCommand property with enough information tofind this temporary file.• If a word processor were sent a ‘‘Save Yourself’’ witha type of SmSaveGlobal, it would simply save thecurrently edited file.• If a word processor were sent a ‘‘Save Yourself’’ witha type of SmSaveBoth, it would first save the currentlyedited file. It would then create a temporary filewith information such as the current position of thecursor and what file is being edited. Finally, itwould update its SmRestartCommand property with enoughinformation to find the temporary file.The shutdown argument specifies whether the system is beingshut down. The interaction is different depending onwhether or not shutdown is set. If not shutting down, theclient should save its state and wait for a ‘‘SaveComplete’’ message. If shutting down, the client must savestate and then prevent interaction until it receives eithera ‘‘Die’’ or a ‘‘Shutdown Cancelled.’’The fast argument specifies that the client should save itsstate as quickly as possible. For example, if the sessionmanager knows that power is about to fail, it would set fastto True.5.1.2. The Die CallbackThe Die callback is of type SmcDieProc.__│ typedef void (*SmcDieProc)();void DieProc(smc_conn, client_data)SmcConn smc_conn;SmPointer client_data;smc_conn The session management connection object.client_dataClient data specified when the callback wasregistered.│__The session manager sends a ‘‘Die’’ message to a client whenit wants it to die. The client should respond by callingSmcCloseConnection. A session manager that behaves properlywill send a ‘‘Save Yourself’’ message before the ‘‘Die’’message.5.1.3. The Save Complete CallbackThe Save Complete callback is of type SmcSaveCompleteProc.__│ typedef void (*SmcSaveCompleteProc)();void SaveCompleteProc(smc_conn, client_data)SmcConn smc_conn;SmPointer client_data;smc_conn The session management connection object.client_dataClient data specified when the callback wasregistered.│__When the session manager is done with a checkpoint, it willsend each of the clients a ‘‘Save Complete’’ message. Theclient is then free to change its state.5.1.4. The Shutdown Cancelled CallbackThe Shutdown Cancelled callback is of typeSmcShutdownCancelledProc.__│ typedef void (*SmcShutdownCancelledProc)();void ShutdownCancelledProc(smc_conn, client_data)SmcConn smc_conn;SmPointer client_data;smc_conn The session management connection object.client_dataClient data specified when the callback wasregistered.│__The session manager sends a ‘‘Shutdown Cancelled’’ messagewhen the user cancelled the shutdown during an interaction(see section 5.5, ‘‘Interacting With the User’’). Theclient can now continue as if the shutdown had neverhappened. If the client has not called SmcSaveYourselfDoneyet, it can either abort the save and then callSmcSaveYourselfDone with the success argument set to False,or it can continue with the save and then callSmcSaveYourselfDone with the success argument set to reflectthe outcome of the save.5.2. Closing the ConnectionTo close a connection with a session manager, useSmcCloseConnection.__│ SmcCloseStatus SmcCloseConnection(smc_conn, count, reason_msgs)SmcConn smc_conn;int count;char **reason_msgs;smc_conn The session management connection object.count The number of reason messages.reason_msgsThe reasons for closing the connection.│__The reason_msgs argument will most likely be NULL ifresignation is expected by the client. Otherwise, itcontains a list of null-terminated Compound Text stringsrepresenting the reason for termination. The sessionmanager should display these reason messages to the user.Note that SMlib used the ICE protocol to establish aconnection with the session manager, and various protocolsother than session management may be active on the ICEconnection. When SmcCloseConnection is called, the ICEconnection will be closed only if all protocols have beenshutdown on the connection. Check the ICElib standard forIceAddConnectionWatch and IceRemoveConnectionWatch to learnhow to set up a callback to be invoked each time an ICEconnection is opened or closed. Typically this callbackadds/removes the ICE file descriptor from the list of activedescriptors to call select on (or calls XtAppAddInput orXtRemoveInput).SmcCloseConnection returns one of the following values:• SmcClosedNow − the ICE connection was closed at thistime, the watch procedures were invoked, and theconnection was freed.• SmcClosedASAP − an IO error had occurred on theconnection, but SmcCloseConnection is being calledwithin a nested IceProcessMessages. The watchprocedures have been invoked at this time, but theconnection will be freed as soon as possible (when thenesting level reaches zero and IceProcessMessagesreturns a status ofIceProcessMessagesConnectionClosed).• SmcConnectionInUse − the connection was not closed atthis time, because it is being used by other activeprotocols.5.3. Modifying CallbacksTo modify callbacks set up in SmcOpenConnection, useSmcModifyCallbacks.__│ void SmcModifyCallbacks(smc_conn, mask, callbacks)SmcConn smc_conn;unsigned long mask;SmcCallbacks *callbacks;smc_conn The session management connection object.mask A mask indicating which callbacks to modify.callbacks The new callbacks.│__When specifying a value for the mask argument, the followingvalues may be ORed together:SmcSaveYourselfProcMaskSmcDieProcMaskSmcSaveCompleteProcMaskSmcShutdownCancelledProcMask5.4. Setting, Deleting, and Retrieving Session ManagementPropertiesTo set session management properties for this client, useSmcSetProperties.__│ void SmcSetProperties(smc_conn, num_props, props)SmcConn smc_conn;int num_props;SmProp **props;smc_conn The session management connection object.num_props The number of properties.props The list of properties to set.│__The properties are specified as an array of propertypointers. Previously set property values may beover-written using the SmcSetProperties function. Note thatthe session manager is not expected to restore propertyvalues when the session is restarted. Because of this,clients should not try to use the session manager as adatabase for storing application specific state.For a description of session management properties and theSmProp structure, see section 7, ‘‘Session ManagementProperties.’’To delete properties previously set by the client, useSmcDeleteProperties.__│ void SmcDeleteProperties(smc_conn, num_props, prop_names)SmcConn smc_conn;int num_props;char **prop_names;smc_conn The session management connection object.num_props The number of properties.prop_namesThe list of properties to delete.│__To get properties previously stored by the client, useSmcGetProperties.__│ Status SmcGetProperties(smc_conn, prop_reply_proc, client_data)SmcConn smc_conn;SmcPropReplyProc prop_reply_proc;SmPointer client_data;smc_conn The session management connection object.prop_reply_procThe callback to be invoked when the propertiesreply comes back.client_dataThis pointer to client data will be passed to theSmcPropReplyProc callback.│__The return value of SmcGetProperties is zero for failure anda positive value for success.Note that the library does not block until the propertiesreply comes back. Rather, a callback of typeSmcPropReplyProc is invoked when the data is ready.__│ typedef void (*SmcPropReplyProc)();void PropReplyProc(smc_conn, client_data, num_props, props)SmcConn smc_conn;SmPointer client_data;int num_props;SmProp **props;smc_conn The session management connection object.client_dataClient data specified when the callback wasregistered.num_props The number of properties returned.props The list of properties returned.│__To free each property, use SmFreeProperty (see section 8,‘‘Freeing Data’’). To free the actual array of pointers,use free.5.5. Interacting With the UserAfter receiving a ‘‘Save Yourself’’ message with aninteract_style of SmInteractStyleErrors orSmInteractStyleAny, the client may choose to interact withthe user. Because only one client can interact with theuser at a time, the client must call SmcInteractRequest andwait for an ‘‘Interact’’ message from the session manager.__│ Status SmcInteractRequest(smc_conn, dialog_type, interact_proc, client_data)SmcConn smc_conn;int dialog_type;SmcInteractProc interact_proc;SmPointer client_data;smc_conn The session management connection object.dialog_typeThe type of dialog the client wishes to present tothe user.interact_procThe callback to be invoked when the ‘‘Interact’’message arrives from the session manager.client_dataThis pointer to client data will be passed to theSmcInteractProc callback when the ‘‘Interact’’message arrives.│__The return value of SmcInteractRequest is zero for failureand a positive value for success.The dialog_type argument specifies either SmDialogError,indicating that the client wants to start an error dialog,or SmDialogNormal, meaning that the client wishes to start anonerror dialog.Note that if a shutdown is in progress, the user may havethe option of cancelling the shutdown. If the shutdown iscancelled, the clients that have not interacted yet with theuser will receive a ‘‘Shutdown Cancelled’’ message insteadof the ‘‘Interact’’ message.The SmcInteractProc callback will be invoked when the‘‘Interact’’ message arrives from the session manager.__│ typedef void (*SmcInteractProc)();void InteractProc(smc_conn, client_data)SmcConn smc_conn;SmPointer client_data;smc_conn The session management connection object.client_dataClient data specified when the callback wasregistered.│__After interacting with the user (in response to an‘‘Interact’’ message), you should call SmcInteractDone.__│ void SmcInteractDone(smc_conn, cancel_shutdown)SmcConn smc_conn;Bool cancel_shutdown;smc_conn The session management connection object.cancel_shutdownIf True, indicates that the user requests that theentire shutdown be cancelled.│__The cancel_shutdown argument may only be True if thecorresponding ‘‘Save Yourself’’ specified True for shutdownand SmInteractStyleErrors or SmInteractStyleAny for theinteract_style.5.6. Requesting a Save YourselfTo request a checkpoint from the session manager, useSmcRequestSaveYourself.__│ void SmcRequestSaveYourself(smc_conn, save_type, shutdown, interact_style, fast, global)SmcConn smc_conn;int save_type;Bool shutdown;int interact_style;Bool fast;Bool global;smc_conn The session management connection object.save_type Specifies the type of information that should besaved.shutdown Specifies if a shutdown is taking place.interact_styleThe type of interaction allowed with the user.fast If True, the client should save its state asquickly as possible.global Controls who gets the ‘‘Save Yourself.’’│__The save_type, shutdown, interact_style, and fast argumentsare discussed in more detail in section 5.1.1, ‘‘The SaveYourself Callback.’’If global is set to True, then the resulting ‘‘SaveYourself’’ should be sent to all clients in the session.For example, a vendor of a Uninterruptible Power Supply(UPS) might include a Session Management client that wouldmonitor the status of the UPS and generate a fast shutdownif the power is about to be lost.If global is set to False, then the ‘‘Save Yourself’’ shouldonly be sent to the client that requested it.5.7. Requesting a Save Yourself Phase 2In response to a ‘‘Save Yourself, the client may request tobe informed when all the other clients are quiescent so thatit can save their state. To do so, useSmcRequestSaveYourselfPhase2.__│ Status SmcRequestSaveYourselfPhase2(smc_conn, save_yourself_phase2_proc, client_data)SmcConn smc_conn;SmcSaveYourselfPhase2Proc save_yourself_phase2_proc;SmPointer client_data;smc_conn The session management connection object.save_yourself_phase2_procThe callback to be invoked when the ‘‘SaveYourself Phase 2’’ message arrives from thesession manager.client_dataThis pointer to client data will be passed to theSmcSaveYourselfPhase2Proc callback when the ‘‘SaveYourself Phase 2’’ message arrives.│__The return value of SmcRequestSaveYourselfPhase2 is zero forfailure and a positive value for success.This request is needed by clients that manage other clients(for example, window managers, workspace managers, and soon). The manager must make sure that all of the clientsthat are being managed are in an idle state so that theirstate can be saved.5.8. Completing a Save YourselfAfter saving state in response to a ‘‘Save Yourself’’message, you should call SmcSaveYourselfDone.__│ void SmcSaveYourselfDone(smc_conn, success)SmcConn smc_conn;Bool success;smc_conn The session management connection object.success If True, the ‘‘Save Yourself’’ operation wascompleted successfully.│__Before calling SmcSaveYourselfDone, the client must have seteach required property at least once since the clientregistered with the session manager.5.9. Using Smc Informational Functions__│ int SmcProtocolVersion(smc_conn)SmcConn smc_conn;│__SmcProtocolVersion returns the major version of the sessionmanagement protocol associated with this session.__│ int SmcProtocolRevision(smc_conn)SmcConn smc_conn;│__SmcProtocolRevision returns the minor version of the sessionmanagement protocol associated with this session.__│ char *SmcVendor(smc_conn)SmcConn smc_conn;│__SmcVendor returns a string that provides some identificationof the owner of the session manager. The string should befreed with a call to free.__│ char *SmcRelease(smc_conn)SmcConn smc_conn;│__SmcRelease returns a string that provides the release numberof the session manager. The string should be freed with acall to free.__│ char *SmcClientID(smc_conn)SmcConn smc_conn;│__SmcClientID returns a null-terminated string for the clientID associated with this connection. This information wasalso returned in SmcOpenConnection (it is provided here forconvenience). Call free on this pointer when the client IDis no longer needed.__│ IceConn SmcGetIceConnection(smc_conn)SmcConn smc_conn;│__SmcGetIceConnection returns the ICE connection objectassociated with this session management connection object.The ICE connection object can be used to get some additionalinformation about the connection. Some of the more usefulfunctions which can be used on the IceConn areIceConnectionNumber, IceConnectionString,IceLastSentSequenceNumber, IceLastReceivedSequenceNumber,and IcePing. For further information, see the Inter-ClientExchange Library standard.5.10. Error HandlingIf the client receives an unexpected protocol error from thesession manager, an error handler is invoked by SMlib. Adefault error handler exists that simply prints the errormessage to stderr and exits if the severity of the error isfatal. The client can change this error handler by callingthe SmcSetErrorHandler function.__│ SmcErrorHandler SmcSetErrorHandler(handler)SmcErrorHandler handler;handler The error handler. You should pass NULL torestore the default handler.│__SmcSetErrorHandler returns the previous error handler.The SmcErrorHandler has the following type:__│ typedef void (*SmcErrorHandler)();void ErrorHandler(smc_conn, swap, offending_minor_opcode, offending_sequence_num, error_class, severity, values)SmcConn smc_conn;Bool swap;int offending_minor_opcode;unsigned long offending_sequence_num;int error_class;int severity;IcePointer values;smc_conn The session management connection object.swap A flag that indicates if the specified values needbyte swapping.offending_minor_opcodeThe minor opcode of the offending message.offending_sequence_numThe sequence number of the offending message.error_classThe error class of the offending message.severity IceCanContinue, IceFatalToProtocol, orIceFatalToConnection.values Any additional error values specific to the minoropcode and class.│__Note that this error handler is invoked for protocol relatederrors. To install an error handler to be invoked when anIO error occurs, use IceSetIOErrorHandler. For furtherinformation, see the Inter-Client Exchange Library standard.6. Session Management Server (Sms) FunctionsThis section discusses how Session Management servers:• Initialize the library• Register the client• Send a ‘‘Save Yourself’’ message• Send a ‘‘Save Yourself Phase 2’’ message• Send an ‘‘Interact’’ message• Send a ‘‘Save Complete’’ message• Send a ‘‘Die’’ message• Cancel a shutdown• Return properties• Ping a client• Clean up after a client disconnects• Use Sms informational functions• Handle errors6.1. Initializing the LibrarySmsInitialize is the first SMlib function that should becalled by a session manager. It provides information aboutthe session manager and registers a callback that will beinvoked each time a new client connects to the sessionmanager.__│ Status SmsInitialize(vendor, release, new_client_proc, manager_data, host_based_auth_proc,error_length, error_string_ret)char *vendor;char *release;SmsNewClientProc new_client_proc;SmPointer manager_data;IceHostBasedAuthProc host_based_auth_proc;int error_length;char *error_string_ret;vendor A string specifying the session manager vendor.release A string specifying the session manager releasenumber.new_client_procCallback to be invoked each time a new clientconnects to the session manager.manager_dataWhen the SmsNewClientProc callback is invoked,this pointer to manager data will be passed.host_based_auth_procHost based authentication callback.error_lengthLength of the error_string_ret argument passed in.error_string_retReturns a null-terminated error message, if any.The error_string_ret points to user suppliedmemory. No more than error_length bytes are used.│__After the SmsInitialize function is called, the sessionmanager should call the IceListenForConnections function tolisten for new connections. Afterwards, each time a clientconnects, the session manager should callIceAcceptConnection.See section 9, ‘‘Authentication of Clients,’’ for moredetails on authentication (including host basedauthentication). Also see the Inter-Client Exchange Librarystandard for further details on listening for and acceptingICE connections.Each time a new client connects to the session manager, theSmsNewClientProc callback is invoked. The session managerobtains a new opaque connection object that it should usefor all future interaction with the client. At this time,the session manager must also register a set of callbacks torespond to the different messages that the client mightsend.__│ typedef Status (*SmsNewClientProc)();Status NewClientProc(sms_conn, manager_data, mask_ret, callbacks_ret, failure_reason_ret)SmsConn sms_conn;SmPointer manager_data;unsigned long *mask_ret;SmsCallbacks *callbacks_ret;char **failure_reason_ret;sms_conn A new opaque connection object.manager_dataManager data specified when the callback wasregistered.mask_ret On return, indicates which callbacks were set bythe session manager.callbacks_retOn return, contains the callbacks registered bythe session manager.failure_reason_retFailure reason returned.│__If a failure occurs, the SmsNewClientProc should return azero status as well as allocate and return a failure reasonstring in failure_reason_ret. SMlib will be responsible forfreeing this memory.The session manager must register a set of callbacks torespond to client events. The mask_ret argument specifieswhich callbacks are set. All of the callbacks specified inthis version of SMlib are mandatory. The mask_ret argumentis necessary in order to maintain backwards compatibility infuture versions of the library.The following values may be ORed together to obtain a maskvalue:SmsRegisterClientProcMaskSmsInteractRequestProcMaskSmsInteractDoneProcMaskSmsSaveYourselfRequestProcMaskSmsSaveYourselfP2RequestProcMaskSmsSaveYourselfDoneProcMaskSmsCloseConnectionProcMaskSmsSetPropertiesProcMaskSmsDeletePropertiesProcMaskSmsGetPropertiesProcMaskFor each callback, the session manager can register apointer to manager data specific to that callback. Thispointer will be passed to the callback when it is invoked bySMlib.__│ typedef struct {struct {SmsRegisterClientProc callback;SmPointer manager_data;} register_client;struct {SmsInteractRequestProc callback;SmPointer manager_data;} interact_request;struct {SmsInteractDoneProc callback;SmPointer manager_data;} interact_done;struct {SmsSaveYourselfRequestProc callback;SmPointer manager_data;} save_yourself_request;struct {SmsSaveYourselfPhase2RequestProc callback;SmPointer manager_data;} save_yourself_phase2_request;struct {SmsSaveYourselfDoneProc callback;SmPointer manager_data;} save_yourself_done;struct {SmsCloseConnectionProc callback;SmPointer manager_data;} close_connection;struct {SmsSetPropertiesProc callback;SmPointer manager_data;} set_properties;struct {SmsDeletePropertiesProc callback;SmPointer manager_data;} delete_properties;struct {SmsGetPropertiesProc callback;SmPointer manager_data;} get_properties;} SmsCallbacks;│__6.1.1. The Register Client CallbackThe Register Client callback is the first callback that willbe invoked after the client connects to the session manager.Its type is SmsRegisterClientProc.__│ typedef Status (*SmsRegisterClientProc();Status RegisterClientProc(sms_conn, manager_data, previous_id)SmsConn sms_conn;SmPointer manager_data;char *previous_id;sms_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.previous_idThe client ID from the previous session.│__Before any further interaction takes place with the client,the client must be registered with the session manager.If the client is being restarted from a previous session,previous_id will contain a null-terminated stringrepresenting the client ID from the previous session. Callfree on the previous_id pointer when it is no longer needed.If the client is first joining the session, previous_id willbe NULL.If previous_id is invalid, the session manager should notregister the client at this time. This callback shouldreturn a status of zero, which will cause an error messageto be sent to the client. The client should re-registerwith previous_id set to NULL.Otherwise, the session manager should register the clientwith a unique client ID by calling theSmsRegisterClientReply function (to be discussed shortly),and the SmsRegisterClientProc callback should return astatus of one.6.1.2. The Interact Request CallbackThe Interact Request callback is of typeSmsInteractRequestProc.__│ typedef void (*SmsInteractRequestProc)();void InteractRequestProc(sms_conn, manager_data, dialog_type)SmsConn sms_conn;SmPointer manager_data;int dialog_type;sms_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.dialog_typeThe type of dialog the client wishes to present tothe user.│__When a client receives a ‘‘Save Yourself’’ message with aninteract_style of SmInteractStyleErrors orSmInteractStyleAny, the client may choose to interact withthe user. Because only one client can interact with theuser at a time, the client must request to interact with theuser. The session manager should keep a queue of allclients wishing to interact. It should send an ‘‘Interact’’message to one client at a time and wait for an ‘‘InteractDone’’ message before continuing with the next client.The dialog_type argument specifies either SmDialogError,indicating that the client wants to start an error dialog,or SmDialogNormal, meaning that the client wishes to start anonerror dialog.If a shutdown is in progress, the user may have the optionof cancelling the shutdown. If the shutdown is cancelled(specified in the ‘‘Interact Done’’ message), the sessionmanager should send a ‘‘Shutdown Cancelled’’ message to eachclient that requested to interact.6.1.3. The Interact Done CallbackWhen the client is done interacting with the user, theSmsInteractDoneProc callback will be invoked.__│ typedef void (*SmsInteractDoneProc)();void InteractDoneProc(sms_conn, manager_data, cancel_shutdown)SmsConn sms_conn;SmPointer manager_data;Bool cancel_shutdown;sms_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.cancel_shutdownSpecifies if the user requests that the entireshutdown be cancelled.│__Note that the shutdown can be cancelled only if thecorresponding ‘‘Save Yourself’’ specified True for shutdownand SmInteractStyleErrors or SmInteractStyleAny for theinteract_style.6.1.4. The Save Yourself Request CallbackThe Save Yourself Request callback is of typeSmsSaveYourselfRequestProc.__│ typedef void (*SmsSaveYourselfRequestProc)();void SaveYourselfRequestProc(sms_conn, manager_data, save_type, shutdown, interact_style, fast, global)SmsConn sms_conn;SmPointer manager_data;int save_type;Bool shutdown;int interact_style;Bool fast;Bool global;sms_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.save_type Specifies the type of information that should besaved.shutdown Specifies if a shutdown is taking place.interact_styleThe type of interaction allowed with the user.fast If True, the client should save its state asquickly as possible.global Controls who gets the ‘‘Save Yourself.’’│__The Save Yourself Request prompts the session manager toinitiate a checkpoint or shutdown. For information on thesave_type, shutdown, interact_style, and fast arguments, seesection 6.3, ‘‘Sending a Save Yourself Message.’’If global is set to True, then the resulting ‘‘SaveYourself’’ should be sent to all applications. If global isset to False, then the ‘‘Save Yourself’’ should only be sentto the client that requested it.6.1.5. The Save Yourself Phase 2 Request CallbackThe Save Yourself Phase 2 Request callback is of typeSmsSaveYourselfPhase2RequestProc.__│ typedef void (*SmsSaveYourselfPhase2RequestProc)();void SmsSaveYourselfPhase2RequestProc(sms_conn, manager_data)SmsConn sms_conn;SmPointer manager_data;sms_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.│__This request is sent by clients that manage other clients(for example, window managers, workspace managers, and soon). Such managers must make sure that all of the clientsthat are being managed are in an idle state so that theirstate can be saved.6.1.6. The Save Yourself Done CallbackWhen the client is done saving its state in response to a‘‘Save Yourself’’ message, the SmsSaveYourselfDoneProc willbe invoked.__│ typedef void (*SmsSaveYourselfDoneProc)();void SaveYourselfDoneProc(sms_conn, manager_data, success)SmsConn sms_conn;SmPointer manager_data;Bool success;sms_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.success If True, the Save Yourself operation was completedsuccessfully.│__Before the ‘‘Save Yourself Done’’ was sent, the client musthave set each required property at least once since itregistered with the session manager.6.1.7. The Connection Closed CallbackIf the client properly terminates (that is, it callsSmcCloseConnection), the SmsCloseConnectionProc callback isinvoked.__│ typedef void (*SmsCloseConnectionProc)();void CloseConnectionProc(sms_conn, manager_data, count, reason_msgs)SmsConn sms_conn;SmPointer manager_data;int count;char **reason_msgs;sms_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.count The number of reason messages.reason_msgsThe reasons for closing the connection.│__The reason_msgs argument will most likely be NULL and thecount argument zero (0) if resignation is expected by theuser. Otherwise, it contains a list of null-terminatedCompound Text strings representing the reason fortermination. The session manager should display thesereason messages to the user.Call SmFreeReasons to free the reason messages. For furtherinformation, see section 8, ‘‘Freeing Data.’’6.1.8. The Set Properties CallbackWhen the client sets session management properties, theSmsSetPropertiesProc callback will be invoked.__│ typedef void (*SmsSetPropertiesProc)();void SetPropertiesProc(sms_conn, manager_data, num_props, props)SmsConn sms_conn;SmPointer manager_data;int num_props;SmProp **props;smc_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.num_props The number of properties.props The list of properties to set.│__The properties are specified as an array of propertypointers. For a description of session managementproperties and the SmProp structure, see section 7,‘‘Session Management Properties.’’Previously set property values may be over-written. Someproperties have predefined semantics. The session manageris required to store nonpredefined properties.To free each property, use SmFreeProperty. For furtherinformation, see section 8, ‘‘Freeing Data.’’ You shouldfree the actual array of pointers with a call to free.6.1.9. The Delete Properties CallbackWhen the client deletes session management properties, theSmsDeletePropertiesProc callback will be invoked.__│ typedef void (*SmsDeletePropertiesProc)();void DeletePropertiesProc(sms_conn, manager_data, num_props, prop_names)SmsConn sms_conn;SmPointer manager_data;int num_props;char **prop_names;smc_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.num_props The number of properties.prop_namesThe list of properties to delete.│__The properties are specified as an array of strings. For adescription of session management properties and the SmPropstructure, see section 7, ‘‘Session Management Properties.’’6.1.10. The Get Properties CallbackThe SmsGetPropertiesProc callback is invoked when the clientwants to retrieve properties it set.__│ typedef void (*SmsGetPropertiesProc)();void GetPropertiesProc(sms_conn, manager_data)SmsConn sms_conn;SmPointer manager_data;smc_conn The session management connection object.manager_dataManager data specified when the callback wasregistered.│__The session manager should respond by callingSmsReturnProperties. All of the properties set for thisclient should be returned.6.2. Registering the ClientTo register a client (in response to a SmsRegisterClientProccallback), use SmsRegisterClientReply.__│ Status SmsRegisterClientReply(sms_conn, client_id)SmsConn sms_conn;char *client_id;sms_conn The session management connection object.client_id A null-terminated string representing a uniqueclient ID.│__The return value of SmsRegisterClientReply is zero forfailure and a positive value for success. Failure willoccur if SMlib can not allocate memory to hold a copy of theclient ID for it’s own internal needs.If a non-NULL previous_id was specified when the clientregistered itself, client_id should be identical toprevious_id.Otherwise, client_id should be a unique ID freshly generatedby the session manager. In addition, the session managershould send a ‘‘Save Yourself’’ message with type = Local,shutdown = False, interact-style = None, and fast = Falseimmediately after registering the client.Note that once a client ID has been assigned to the client,the client keeps this ID indefinitely. If the client isterminated and restarted, it will be reassigned the same ID.It is desirable to be able to pass client IDs around frommachine to machine, from user to user, and from sessionmanager to session manager, while retaining the identity ofthe client. This, combined with the indefinite persistenceof client IDs, means that client IDs need to be globallyunique.You should call the SmsGenerateClientID function to generatea globally unique client ID.__│ char *SmsGenerateClientID(sms_conn)SmsConn sms_conn;sms_conn The session management connection object.│__NULL will be returned if the ID could not be generated.Otherwise, the return value of the function is the clientID. It should be freed with a call to free when no longerneeded.6.3. Sending a Save Yourself MessageTo send a ‘‘Save Yourself’’ to a client, useSmsSaveYourself.__│ void SmsSaveYourself(sms_conn, save_type, shutdown, interact_style, fast)SmsConn sms_conn;int save_type;Bool shutdown;int interact_style;Bool fast;sms_conn The session management connection object.save_type Specifies the type of information that should besaved.shutdown Specifies if a shutdown is taking place.interact_styleThe type of interaction allowed with the user.fast If True, the client should save its state asquickly as possible.│__The session manager sends a ‘‘Save Yourself’’ message to aclient either to checkpoint it or just before termination sothat it can save its state. The client responds with zeroor more ‘‘Set Properties’’ messages to update the propertiesindicating how to restart the client. When all theproperties have been set, the client sends a ‘‘Save YourselfDone’’ message.If interact_style is SmInteractStyleNone, the client mustnot interact with the user while saving state. Ifinteract_style is SmInteractStyleErrors, the client mayinteract with the user only if an error condition arises.If interact_style is SmInteractStyleAny, then the client mayinteract with the user for any purpose. The client mustsend an ‘‘Interact Request’’ message and wait for an‘‘Interact’’ message from the session manager before it caninteract with the user. When the client is done interactingwith the user, it should send an ‘‘Interact Done’’ message.The ‘‘Interact Request’’ message can be sent any time aftera ‘‘Save Yourself’’ and before a ‘‘Save Yourself Done.’’If save_type is SmSaveLocal, the client must update theproperties to reflect its current state. Specifically, itshould save enough information to restore the state as seenby the user of this client. It should not affect the stateas seen by other users. If save_type is SmSaveGlobal theuser wants the client to commit all of its data topermanent, globally accessible storage. If save_type isSmSaveBoth, the client should do both of these (it shouldfirst commit the data to permanent storage before updatingits properties).The shutdown argument specifies whether the session is beingshut down. The interaction is different depending onwhether or not shutdown is set. If not shutting down, thenthe client can save and resume normal operation. Ifshutting down, the client must save and then must preventinteraction until it receives either a ‘‘Die’’ or a‘‘Shutdown Cancelled,’’ because anything the user does afterthe save will be lost.The fast argument specifies that the client should save itsstate as quickly as possible. For example, if the sessionmanager knows that power is about to fail, it should setfast to True.6.4. Sending a Save Yourself Phase 2 MessageIn order to send a ‘‘Save Yourself Phase 2’’ message to aclient, use SmsSaveYourselfPhase2.__│ void SmsSaveYourselfPhase2(sms_conn)SmsConn sms_conn;sms_conn The session management connection object.│__The session manager sends this message to a client that haspreviously sent a ‘‘Save Yourself Phase 2 Request’’ message.This message informs the client that all other clients arein a fixed state and this client can save state that isassociated with other clients.6.5. Sending an Interact MessageTo send an ‘‘Interact’’ message to a client, useSmsInteract.__│ void SmsInteract(sms_conn)SmsConn sms_conn;sms_conn The session management connection object.│__The ‘‘Interact’’ message grants the client the privilege ofinteracting with the user. When the client is doneinteracting with the user, it must send an ‘‘Interact Done’’message to the session manager.6.6. Sending a Save Complete MessageTo send a ‘‘Save Complete’’ message to a client, useSmsSaveComplete.__│ void SmsSaveComplete(sms_conn)SmsConn sms_conn;sms_conn The session management connection object.│__The session manager sends this message when it is done witha checkpoint. The client is then free to change its state.6.7. Sending a Die MessageTo send a ‘‘Die’’ message to a client, use SmsDie.__│ void SmsDie(sms_conn)SmsConn sms_conn;sms_conn The session management connection object.│__Before the session manager terminates, it should wait for a‘‘Connection Closed’’ message from each client that it senta ‘‘Die’’ message to, timing out appropriately.6.8. Cancelling a ShutdownTo cancel a shutdown, use SmsShutdownCancelled.__│ void SmsShutdownCancelled(sms_conn)SmsConn sms_conn;sms_conn The session management connection object.│__The client can now continue as if the shutdown had neverhappened. If the client has not sent a ‘‘Save YourselfDone’’ message yet, it can either abort the save and send a‘‘Save Yourself Done’’ with the success argument set toFalse, or it can continue with the save and send a ‘‘SaveYourself Done’’ with the success argument set to reflect theoutcome of the save.6.9. Returning PropertiesIn response to a ‘‘Get Properties’’ message, the sessionmanager should call SmsReturnProperties.__│ void SmsReturnProperties(sms_conn, num_props, props)SmsConn sms_conn;int num_props;SmProp **props;sms_conn The session management connection object.num_props The number of properties.props The list of properties to return to the client.│__The properties are returned as an array of propertypointers. For a description of session managementproperties and the SmProp structure, see section 7,‘‘Session Management Properties.’’6.10. Pinging a ClientTo check that a client is still alive, you should use theIcePing function provided by the ICE library. To do so, theICE connection must be obtained using theSmsGetIceConnection (see section 6.12, ‘‘Using SmsInformational Functions’’).__│ void IcePing(ice_conn, ping_reply_proc, client_data)IceConn ice_conn;IcePingReplyProc ping_reply_proc;IcePointer client_data;ice_conn A valid ICE connection object.ping_reply_procThe callback to invoke when the Ping replyarrives.client_dataThis pointer will be passed to theIcePingReplyProc callback.│__When the Ping reply is ready (if ever), the IcePingReplyProccallback will be invoked. A session manager should havesome sort of timeout period, after which it assumes theclient has unexpectedly died.__│ typedef void (*IcePingReplyProc)();void PingReplyProc(ice_conn, client_data)IceConn ice_conn;IcePointer client_data;ice_conn The ICE connection object.client_dataThe client data specified in the call to IcePing.│__6.11. Cleaning Up After a Client DisconnectsWhen the session manager receives a ‘‘Connection Closed’’message or otherwise detects that the client aborted theconnection, it should call the SmsCleanUp function in orderto free up the connection object.__│ void SmsCleanUp(sms_conn)SmsConn sms_conn;sms_conn The session management connection object.│__6.12. Using Sms Informational Functions__│ int SmsProtocolVersion(sms_conn)SmsConn sms_conn;│__SmsProtocolVersion returns the major version of the sessionmanagement protocol associated with this session.__│ int SmsProtocolRevision(sms_conn)SmsConn sms_conn;│__SmsProtocolRevision returns the minor version of the sessionmanagement protocol associated with this session.__│ char *SmsClientID(sms_conn)SmsConn sms_conn;│__SmsClientID returns a null-terminated string for the clientID associated with this connection. You should call free onthis pointer when the client ID is no longer needed.To obtain the host name of a client, use SmsClientHostName.This host name will be needed to restart the client.__│ char *SmsClientHostName(sms_conn)SmsConn sms_conn;│__The string returned is of the form protocol/hostname, whereprotocol is one of {tcp, decnet, local}. You should callfree on the string returned when it is no longer needed.__│ IceConn SmsGetIceConnection(sms_conn)SmsConn sms_conn;│__SmsGetIceConnection returns the ICE connection objectassociated with this session management connection object.The ICE connection object can be used to get some additionalinformation about the connection. Some of the more usefulfunctions which can be used on the IceConn areIceConnectionNumber, and IceLastSequenceNumber. For furtherinformation, see the Inter-Client Exchange Library standard.6.13. Error HandlingIf the session manager receives an unexpected protocol errorfrom a client, an error handler is invoked by SMlib. Adefault error handler exists which simply prints the errormessage (it does not exit). The session manager can changethis error handler by calling SmsSetErrorHandler.__│ SmsErrorHandler SmsSetErrorHandler(handler)SmsErrorHandler handler;handler The error handler. You should pass NULL torestore the default handler.│__SmsSetErrorHandler returns the previous error handler. TheSmsErrorHandler has the following type:__│ typedef void (*SmsErrorHandler)();void ErrorHandler(sms_conn, swap, offending_minor_opcode, offending_sequence_num, error_class, severity, values)SmsConn sms_conn;Bool swap;int offending_minor_opcode;unsigned long offending_sequence_num;int error_class;int severity;IcePointer values;sms_conn The session management connection object.swap A flag which indicates if the specified valuesneed byte swapping.offending_minor_opcodeThe minor opcode of the offending message.offending_sequence_numThe sequence number of the offending message.error_classThe error class of the offending message.severity IceCanContinue, IceFatalToProtocol, orIceFatalToConnection.values Any additional error values specific to the minoropcode and class.│__Note that this error handler is invoked for protocol relatederrors. To install an error handler to be invoked when anIO error occurs, use IceSetIOErrorHandler. For furtherinformation, see the Inter-Client Exchange Library standard.7. Session Management PropertiesEach property is defined by the SmProc structure:typedef struct {char *name; /* name of property */char *type; /* type of property */int num_vals; /* number of values */SmPropValue *vals; /* the list of values */} SmProp;typedef struct {int length; /* the length of the value */SmPointer value; /* the value */} SmPropValue;The X Session Management Protocol defines a list ofpredefined properties, several of which are required to beset by the client. The following table specifies thepredefined properties and indicates which ones are required.Each property has a type associated with it.A type of SmCARD8 indicates that there is a single 1-bytevalue. A type of SmARRAY8 indicates that there is a singlearray of bytes. A type of SmLISTofARRAY8 indicates thatthere is a list of array of bytes.* Required if any state is stored in an external repository(for example, state file).• SmCloneCommandThis is like the SmRestartCommand, except it restarts acopy of the application. The only difference is thatthe application does not supply its client ID atregister time. On POSIX systems, this should be oftype SmLISTofARRAY8.• SmCurrentDirectoryOn POSIX-based systems, this specifies the value of thecurrent directory that needs to be set up prior tostarting the SmProgram and should of type SmARRAY8.• SmDiscardCommandThe discard command contains a command that whendelivered to the host that the client is running on(determined from the connection), will cause it todiscard any information about the current state. Ifthis command is not specified, the Session Manager willassume that all of the client’s state is encoded in theSmRestartCommand. On POSIX systems, the type should beSmLISTofARRAY8.• SmEnvironmentOn POSIX based systems, this will be of typeSmLISTofARRAY8, where the ARRAY8s alternate betweenenvironment variable name and environment variablevalue.• SmProcessIDThis specifies an OS-specific identifier for theprocess. On POSIX systems, this should contain thereturn value of getpid turned into a Latin-1 (decimal)string.• SmProgramThis is the name of the program that is running. OnPOSIX systems, this should be first parameter passed toexecve and should be of type SmARRAY8.• SmRestartCommandThe restart command contains a command that, whendelivered to the host that the client is running on(determined from the connection), will cause the clientto restart in its current state. On POSIX-basedsystems, this is of type SmLISTofARRAY8, and each ofthe elements in the array represents an element in theargv array. This restart command should ensure thatthe client restarts with the specified client-ID.• SmResignCommandA client that sets the SmRestartStyleHint toSmRestartAnway uses this property to specify a commandthat undoes the effect of the client and removes anysaved state. As an example, consider a user that runsxmodmap, which registers with the Session Manager, setsSmRestartStyleHint to SmRestartAnyway, and thenterminates. To allow the Session Manager (at theuser’s request) to undo this, xmodmap would register aSmResignCommand that undoes the effects of the xmodmap.• SmRestartStyleHintIf the RestartStyleHint property is present, it willcontain the style of restarting the client prefers. Ifthis style is not specified, SmRestartIfRunning isassumed. The possible values are as follows:The SmRestartIfRunning style is used in the usual case.The client should be restarted in the next session ifit was running at the end of the current session.The SmRestartAnyway style is used to tell the SessionManager that the application should be restarted in thenext session even if it exits before the currentsession is terminated. It should be noted that this isonly a hint and the Session Manager will follow thepolicies specified by its users in determining whatapplications to restart.A client that uses SmRestartAnyway should also set theSmResignCommand and SmShutdownCommand properties tocommands that undo the state of the client after itexits.The SmRestartImmediately style is like SmRestartAnyway,but, in addition, the client is meant to runcontinuously. If the client exits, the Session Managershould try to restart it in the current session.SmRestartNever style specifies that the client does notwish to be restarted in the next session.• SmShutdownCommandThis command is executed at shutdown time to clean upafter a client that is no longer running but retainedits state by setting SmRestartStyleHint toSmRestartAnyway. The client must not remove any savedstate as the client is still part of the session. Asan example, consider a client that turns on a camera atstart up time. This client then exits. At sessionshutdown, the user wants the camera turned off. Thisclient would set the SmRestartStyleHint toSmRestartAnyway and would register a SmShutdownCommandthat would turn off the camera.• SmUserIDSpecifies the user ID. On POSIX-based systems, thiswill contain the user’s name (the pw_name member ofstruct passwd).8. Freeing DataTo free an individual property, use SmFreeProperty.__│ void SmFreeProperty(prop)SmProp *prop;prop The property to free.│__To free the reason strings from the SmsCloseConnectionProccallback, use SmFreeReasons.__│ void SmFreeReasons(count, reasons)int count;char **reasons;count The number of reason strings.reasons The list of reason strings to free.│__9. Authentication of ClientsAs stated earlier, the session management protocol islayered on top of ICE. Authentication occurs at two levelsin the ICE protocol:• The first is when an ICE connection is opened.• The second is when a Protocol Setup occurs on an ICEconnection.The authentication methods that are available areimplementation-dependent (that is., dependent on the ICEliband SMlib implementations in use). For further information,see the Inter-Client Exchange Library standard.10. Working in a Multi-Threaded EnvironmentTo declare that multiple threads in an application will beusing SMlib (or any other library layered on top of ICElib),you should call IceInitThreads. For further information,see the Inter-Client Exchange Library standard.11. AcknowledgementsThanks to the following people for their participation inthe X Session Management design: Jordan Brown, Ellis Cohen,Donna Converse, Stephen Gildea, Vania Joloboff, StuartMarks, Bob Scheifler, Ralph Swick, and Mike Wexler.− 1 −

− 2 −

Table of Contents

1. Overview of Session Management

. . . . . . . . . . .
1

2. The Session Management Library

. . . . . . . . . . .
1

3. Understanding SMlib’s Dependence on ICE

. . . . . . .
1

4. Header Files and Library Name

. . . . . . . . . . . .
1

5. Session Management Client (Smc) Functions

. . . . . .
1

5.1. Connecting to the Session Manager

. . . . . . . . .
1

5.1.1. The Save Yourself Callback

. . . . . . . . . . .
1

5.1.2. The Die Callback

. . . . . . . . . . . . . . . .
1

5.1.3. The Save Complete Callback

. . . . . . . . . . .
1

5.1.4. The Shutdown Cancelled Callback

. . . . . . . . .
1

5.2. Closing the Connection

. . . . . . . . . . . . . .
1

5.3. Modifying Callbacks

. . . . . . . . . . . . . . . .
1
5.4. Setting, Deleting, and Retrieving Session Man-

agement Properties

. . . . . . . . . . . . . . . . . . .
1

5.5. Interacting With the User

. . . . . . . . . . . . .
1

5.6. Requesting a Save Yourself

. . . . . . . . . . . .
1

5.7. Requesting a Save Yourself Phase 2

. . . . . . . .
1

5.8. Completing a Save Yourself

. . . . . . . . . . . .
1

5.9. Using Smc Informational Functions

. . . . . . . . .
1

5.10. Error Handling

. . . . . . . . . . . . . . . . . .
1

6. Session Management Server (Sms) Functions

. . . . . .
1

6.1. Initializing the Library

. . . . . . . . . . . . .
1

6.1.1. The Register Client Callback

. . . . . . . . . .
1

6.1.2. The Interact Request Callback

. . . . . . . . . .
1

6.1.3. The Interact Done Callback

. . . . . . . . . . .
1

6.1.4. The Save Yourself Request Callback

. . . . . . .
1

6.1.5. The Save Yourself Phase 2 Request Callback

. . .
1

6.1.6. The Save Yourself Done Callback

. . . . . . . . .
1

6.1.7. The Connection Closed Callback

. . . . . . . . .
1

6.1.8. The Set Properties Callback

. . . . . . . . . . .
1

6.1.9. The Delete Properties Callback

. . . . . . . . .
1

6.1.10. The Get Properties Callback

. . . . . . . . . .
1

6.2. Registering the Client

. . . . . . . . . . . . . .
1

6.3. Sending a Save Yourself Message

. . . . . . . . . .
1

6.4. Sending a Save Yourself Phase 2 Message

. . . . . .
1

6.5. Sending an Interact Message

. . . . . . . . . . . .
1

6.6. Sending a Save Complete Message

. . . . . . . . .
1

6.7. Sending a Die Message

. . . . . . . . . . . . . . .
1

6.8. Cancelling a Shutdown

. . . . . . . . . . . . . . .
1

6.9. Returning Properties

. . . . . . . . . . . . . . .
1

6.10. Pinging a Client

. . . . . . . . . . . . . . . . .
1

6.11. Cleaning Up After a Client Disconnects

. . . . . .
1

6.12. Using Sms Informational Functions

. . . . . . . .
1

6.13. Error Handling

. . . . . . . . . . . . . . . . . .
1

7. Session Management Properties

. . . . . . . . . . . .
1

8. Freeing Data

. . . . . . . . . . . . . . . . . . . .
1

9. Authentication of Clients

. . . . . . . . . . . . . .
1

10. Working in a Multi-Threaded Environment

. . . . . .
1

11. Acknowledgements

. . . . . . . . . . . . . . . . . .
1

iii