473,847 Members | 2,426 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Object-level signal delivery

lpw
I have dilligently reviewed FAQ-lite Section 3.2, "How do I pass a
pointer-to-member-function to a signal handler, X event callback, system
call that starts a thread/task, etc." The only suggestion on how to deliver
a signal to an object is to do it via a global variable and a wrapper
function, a technique that is generally a Bad Idea (due to the usage of a
global variable). I understand that this ng is dedicated to the discussion
of platform-independent C++ issues, and that signals are primarily an
artifact of UNIX. My question is, however, more related to the proper way
of structuring my C++ code rather than the specifics of signal handling.
I've been racking my brain on how to incorporate signal handling into my C++
programs whilst remaining one with the OO nature. I would like to propose a
possible solution, one that, IMHO, is a little cleaner and fits better with
the OO paradigm than simply using global object pointers.

Suppose that we have a program that does a lot of I/O (sockets, pipes,
files, etc.). For each I/O "stream", we have a dedicated handler object.
When the user becomes bored and sends SIGINT to our program, we would like
all our handlers to cleanly close their respective TCP connections, IPC
pipes, etc. With things like connection-oriented sockets, this is often
more involved than merely calling close(). The responsibility to cleanly
shut down a particular I/O "stream" should be delegated to that stream's
handler object. Thus, we need object-level signal delivery to a number of
heterogeneous objects. This can be accomplished by having all those objects
derive from a common base class. The responsibility of that class (let's
call it Interruptible) is to maintain a list of all live Interruptible
objects and invoke the signal handlers of those objects whenever SIGINT is
caught. The code below illustrates this paradigm using a silly Runner class
instead of an I/O handler. But the idea remains the same.

#include <iostream>
#include <string>
#include <list>
#include <cstdlib>
#include <ctime>
#include <signal.h>
#include <unistd.h>

using namespace std;

class Interruptible {

// "global" list of live interruptible objects
static list<Interrupti ble*> instances;

protected:

// all interruptible classes must implement this method
virtual void sigint_handler( ) = 0;

Interruptible() {
// add me to global list of live interruptible objects
instances.push_ back(this);
}

virtual ~Interruptible( ) {
// remove me from global list of live interruptible objects
instances.remov e(this);
}

public:

// the "global" signal handler
static void sigint_handler( int s) {
// call all interruptible objects
list<Interrupti ble*>::const_it erator i;
for (i=instances.be gin(); i!=instances.en d(); i++)
(*i)->sigint_handler ();
// goodbye
exit(0);
}
};

list<Interrupti ble*> Interruptible:: instances;

class Runner : public Interruptible {

string name;

virtual void sigint_handler( ) {
cout << name << " got SIGINT " << endl;
//
// do some cleanup here
//
}

public:

Runner(const string& str) : Interruptible() , name(str) { }

void run() {
cout << name << " is running" << endl;
//
// do something smart and useful here
//
sleep(1+rand()& 3);
}
};

int main(void) {

signal(SIGINT, Interruptible:: sigint_handler) ;

srand(time(NULL ));

Runner obj1("Runner 1");
Runner obj2("Runner 2");

while (true) {
obj1.run();
obj2.run();
}
}
I am most keen on receiving your comments, questions, flames, death threats,
and/or suggestions on the proposed solution. Again, I am more interested in
writing good object-oriented C++ code rather than the platform specific
mechanisms of signal delivery. I would love to hear of other possible
approaches. Just please don't say that this is completely off topic.
Nov 1 '05 #1
2 2215
"lpw" <lw*********@ho tmail.com> wrote in message
news:Fo******** ************@ro gers.com...
I have dilligently reviewed FAQ-lite Section 3.2, "How do I pass a
pointer-to-member-function to a signal handler, X event callback, system
call that starts a thread/task, etc." The only suggestion on how to
deliver
a signal to an object is to do it via a global variable and a wrapper
function, a technique that is generally a Bad Idea (due to the usage of a
global variable). I understand that this ng is dedicated to the
discussion
of platform-independent C++ issues, and that signals are primarily an
artifact of UNIX. My question is, however, more related to the proper way
of structuring my C++ code rather than the specifics of signal handling.
I've been racking my brain on how to incorporate signal handling into my
C++
programs whilst remaining one with the OO nature. I would like to propose
a
possible solution, one that, IMHO, is a little cleaner and fits better
with
the OO paradigm than simply using global object pointers.

Suppose that we have a program that does a lot of I/O (sockets, pipes,
files, etc.). For each I/O "stream", we have a dedicated handler object.
When the user becomes bored and sends SIGINT to our program, we would
like
all our handlers to cleanly close their respective TCP connections, IPC
pipes, etc. With things like connection-oriented sockets, this is often
more involved than merely calling close(). The responsibility to cleanly
shut down a particular I/O "stream" should be delegated to that stream's
handler object. Thus, we need object-level signal delivery to a number of
heterogeneous objects. This can be accomplished by having all those
objects
derive from a common base class. The responsibility of that class (let's
call it Interruptible) is to maintain a list of all live Interruptible
objects and invoke the signal handlers of those objects whenever SIGINT is
caught. The code below illustrates this paradigm using a silly Runner
class
instead of an I/O handler. But the idea remains the same.

#include <iostream>
#include <string>
#include <list>
#include <cstdlib>
#include <ctime>
#include <signal.h>
#include <unistd.h>

using namespace std;

class Interruptible {

// "global" list of live interruptible objects
static list<Interrupti ble*> instances;

protected:

// all interruptible classes must implement this method
virtual void sigint_handler( ) = 0;

Interruptible() {
// add me to global list of live interruptible objects
instances.push_ back(this);
}

virtual ~Interruptible( ) {
// remove me from global list of live interruptible objects
instances.remov e(this);
}

public:

// the "global" signal handler
static void sigint_handler( int s) {
// call all interruptible objects
list<Interrupti ble*>::const_it erator i;
for (i=instances.be gin(); i!=instances.en d(); i++)
(*i)->sigint_handler ();
// goodbye
exit(0);
}
};

list<Interrupti ble*> Interruptible:: instances;

class Runner : public Interruptible {

string name;

virtual void sigint_handler( ) {
cout << name << " got SIGINT " << endl;
//
// do some cleanup here
//
}

public:

Runner(const string& str) : Interruptible() , name(str) { }

void run() {
cout << name << " is running" << endl;
//
// do something smart and useful here
//
sleep(1+rand()& 3);
}
};

int main(void) {

signal(SIGINT, Interruptible:: sigint_handler) ;

srand(time(NULL ));

Runner obj1("Runner 1");
Runner obj2("Runner 2");

while (true) {
obj1.run();
obj2.run();
}
}
I am most keen on receiving your comments, questions, flames, death
threats,
and/or suggestions on the proposed solution. Again, I am more interested
in
writing good object-oriented C++ code rather than the platform specific
mechanisms of signal delivery. I would love to hear of other possible
approaches. Just please don't say that this is completely off topic.


Your problem is going to deal with you not having any form of locking.
Consider your statement:
for (i=instances.be gin(); i!=instances.en d(); i++)
(*i)->sigint_handler ();

What happens when this is running in one thread, and some other thread is
pushing opjects onto the list? I.E. Somewhere you've called sigint_handler
while at the same time some thread is creating a derived of Interruptible.

In your current program this doesn't seem to be a problem as you don't have
any threads creating other threads, but other cases you may want to do that.
Nov 1 '05 #2

lpw wrote:
I have dilligently reviewed FAQ-lite Section 3.2, "How do I pass a
pointer-to-member-function to a signal handler, X event callback, system
call that starts a thread/task, etc."
I have done something similar. We use it as architecture for our
Multitasking projects. Basically it boils down to passing callback
wrappers over an associated queue (or server). All the concurrent (or
psuedo concurrent) threads/task consist of a handler that blocks on a
queue (also known as mailbox) expecting callback wrapper bases only
(use encapsulating teqniques that prevent any thing else from being
sent over mailbox). The callback is then executed on receipt, upon
whereafter the wrapper is destroyed and the queue is monitored again.
It gets interesting - wrappers that handle member functions with
arguments, what if class instances don't exist when the delayed member
function call is made, etc.

It is a kind of nice pattern though, because it allows for marrying OOP
with multitasking, almost abstracting the multitasking from the OOP
specialist.
The only suggestion on how to deliver
a signal to an object is to do it via a global variable and a wrapper
function, a technique that is generally a Bad Idea (due to the usage of a
global variable).
Obviously a global variable is not needed to deliver a wrapper to a
"Worker Thread". Encapsulation can be used - the thread is then
wrapped. Most threads allow arguments on their entry points - an
argument can be the pointer to an object associated with that
particular object. The entry point to the tread itself being a static
member function, therefore having access to instance internals (and
it's associated mailbox).

Point is global variables are not the only way.
I understand that this ng is dedicated to the discussion
of platform-independent C++ issues, and that signals are primarily an
artifact of UNIX. My question is, however, more related to the proper way
of structuring my C++ code rather than the specifics of signal handling.
I don't know about signals, but you can certainly wrap member
functions, and access them in the context associated with a particular
object - if you want to only associate an object with one context.
I've been racking my brain on how to incorporate signal handling into my C++
programs whilst remaining one with the OO nature. I would like to propose a
possible solution, one that, IMHO, is a little cleaner and fits better with
the OO paradigm than simply using global object pointers.
Who ever used global object pointers?
I think I have done something that

Suppose that we have a program that does a lot of I/O (sockets, pipes,
files, etc.). For each I/O "stream", we have a dedicated handler object.
When the user becomes bored and sends SIGINT to our program, we would like
all our handlers to cleanly close their respective TCP connections, IPC
pipes, etc.
I don't think a sigint is required to do this. Using queueing
mechanisms, finishing the current job at hand and then fetching the
next request from a queue should work? IMHO that's the more OO
approach. I've used these types of approaches for comms (TCP/IP).
With things like connection-oriented sockets, this is often
more involved than merely calling close(). The responsibility to cleanly
shut down a particular I/O "stream" should be delegated to that stream's
handler object. Thus, we need object-level signal delivery to a number of
heterogeneous objects. This can be accomplished by having all those objects
derive from a common base class. The responsibility of that class (let's
call it Interruptible) is to maintain a list of all live Interruptible
objects and invoke the signal handlers of those objects whenever SIGINT is
caught.
In who's context does the interruptible object normally execute. In
which context does the sigint handler execute. How does these contexts
influence each other? Sigint handler seems to be in an orthogonal
context in your example.
The code below illustrates this paradigm using a silly Runner class
instead of an I/O handler. But the idea remains the same.

#include <iostream>
#include <string>
#include <list>
#include <cstdlib>
#include <ctime>
#include <signal.h>
#include <unistd.h>

using namespace std;

class Interruptible {

// "global" list of live interruptible objects
static list<Interrupti ble*> instances;

protected:

// all interruptible classes must implement this method
virtual void sigint_handler( ) = 0;

Interruptible() {
// add me to global list of live interruptible objects
instances.push_ back(this);
}

virtual ~Interruptible( ) {
// remove me from global list of live interruptible objects
instances.remov e(this);
}

public:

// the "global" signal handler
static void sigint_handler( int s) {
// call all interruptible objects
list<Interrupti ble*>::const_it erator i;
for (i=instances.be gin(); i!=instances.en d(); i++)
(*i)->sigint_handler ();
// goodbye
exit(0);
}
};

list<Interrupti ble*> Interruptible:: instances;

class Runner : public Interruptible {

string name;

virtual void sigint_handler( ) {
cout << name << " got SIGINT " << endl;
//
// do some cleanup here
//
}

public:

Runner(const string& str) : Interruptible() , name(str) { }

void run() {
cout << name << " is running" << endl;
//
// do something smart and useful here
//
sleep(1+rand()& 3);
}
};

int main(void) {

signal(SIGINT, Interruptible:: sigint_handler) ;

srand(time(NULL ));

Runner obj1("Runner 1");
Runner obj2("Runner 2");

while (true) {
obj1.run();
obj2.run();
}
}
I am most keen on receiving your comments, questions, flames, death threats,
and/or suggestions on the proposed solution. Again, I am more interested in
writing good object-oriented C++ code rather than the platform specific
mechanisms of signal delivery.


We use the command pattern for this. We pass commands (encapsulating
member function pointers and their receivers) between threads using
queues. I have not seen this technique before :-). But maybe I have not
looked enough. A lot of work because you need to build the architecture
- not OS specific, using the bridge pattern, mostly. Has some problems
of itself, but I think they can be overcome - especially now since
boost has arrived. Is this what you had in mind? Communication between
threads in an OO way?

Regards,

W

Nov 3 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

28
20361
by: Daniel | last post by:
Hello =) I have an object which contains a method that should execute every x ms. I can use setInterval inside the object construct like this - self.setInterval('ObjectName.methodName()', this.pinginterval); - but is there no way to do this without using the literal ObjectName? If I write 'this.methodName()' I get "Line 1 Char 1: Object doesn't support this property or method." in IE, and nothing happens in Firebird.
9
8612
by: Keith Rowe | last post by:
Hello, I am trying to reference a Shockwave Flash Object on a vb code behind page in an ASP.NET project and I receive the following error: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx). On the aspx page I have the object tag as follows:
11
9294
by: DrUg13 | last post by:
In java, this seems so easy. You need a new object Object test = new Object() gives me exactly what I want. could someone please help me understand the different ways to do the same thing in C++. I find my self sometimes, trying Object app = Object(); Object *app = Object(); Object app = new Object();
44
2477
by: Steven T. Hatton | last post by:
This may seem like such a simple question, I should be embarrassed to ask it. The FAQ says an object is "A region of storage with associated semantics." OK, what exactly is meant by "associated semantics"? What, if any, associated semantics are shared by all objects? That part seems to go beyond the FAQ. Does anybody know of a resource that discusses (focuses on) this topic? -- p->m == (*p).m == p.m
16
25430
by: sneill | last post by:
How is it possible to take the value of a variable (in this case, MODE_CREATE, MODE_UPDATE, etc) and use that as an object property name? In the following example I want 'oIcon' object to have the properties: mode1, mode2, and mode3. This seems simple but I can't quite figure it out... Any ideas anyone?
9
2816
by: Andrew Au | last post by:
Dear all, I am trying to write a piece of software that use Object Oriented design and implement it with C, I did the following == In Object.h == typedef struct ObjectStructure* Object; Object object_create(); int object_getIntegerAttribute(Object object);
5
2272
by: Matthew | last post by:
I have a nice little Sub that saves data in a class "mySettings" to an XML file. I call it like so: Dim mySettings As mySettings = New mySettings mySettings.value1 = "someText" mySettings.value2 = "otherText" xmlSave("C:\folder\file.xml", mySettings) Here is the sub: Public Shared Sub xmlSave(ByVal path As String, ByVal config As
4
1889
by: Luke Matuszewski | last post by:
Here are some questions that i am interested about and wanted to here an explanation/discussion: 1. (general) Is the objectness in JavaScript was supported from the very first version of it (in browsers) ? What about the new syntax of creating a object using { 'propName1':'propValue1', 'propName2':'propValue2', 'propName3':{ /* another object */ } } - from what version of JScript/JavaScript it was supported (from what browsers versions) ?...
3
2782
by: User1014 | last post by:
A global variable is really just a property of the "Global Object", so what does that make a function defined in the global context? A method of the Global Object? http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Defining_Functions doesn't actually give any insight.
2
2663
by: Ralph | last post by:
Hi I don't understand why it's not working: function schedule(imTop){ this.tdImagesTop = imTop; } schedule.prototype.selectEl = function() { alert(this.tdImagesTop);
0
9727
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10981
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10643
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10706
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9477
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7879
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4521
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4113
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3158
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.