Descriptions of the traditional signal sending facility implemented in UNIX systems sometimes identify the action of ”sending a signal” with ”sending one bit of information.” Is this identification accurate?
Example of such a description
An example of such a description is provided by Advanced Programming in the UNIX Environment, (W. Richard Stevens,Stephen A. Rago), where the description of the sigqueue function (10.20) claims that ”Generally a signal carries one bit of information: the signal itself.”
Why a signal actually carries 0 bit of information
The signal has no state, so its state is described by 0 bits of information. What carries information is merely that a transmission actually occurred.
Sending 2 bits of information is the same as sending 2 times in a row 1 bit of information, so if a signal would convey 1 bit of information, we could send 2 bits of informations to a process by sending it two times (the same) signal, which looks impossible.
I don't think one bit of information from the quote means literally one bit of information in information theory.
Here's my understanding. For a certain signal, there are only two possible states in a certain moment: a signal happens, or it doesn't happen. This binary states can be represented by one bit (0 or 1). By sending a signal to a process, this information is sent to it.
Again, I think you are overthinking this statement, after all, it's a book about programming, not information theory.
According to man 2 kill, the kill function takes pid_t pid and int sig as parameters. So with kill, you can send information via the signal type (int) and that's it.
If you take a look at man 2 sigaction, it describes the information structure that you can handle in your signal handlers:
siginfo_t {
int si_signo; /* Signal number */
int si_errno; /* An errno value */
int si_code; /* Signal code */
int si_trapno; /* Trap number that caused
hardware-generated signal
(unused on most architectures) */
pid_t si_pid; /* Sending process ID */
uid_t si_uid; /* Real user ID of sending process */
int si_status; /* Exit value or signal */
clock_t si_utime; /* User time consumed */
clock_t si_stime; /* System time consumed */
sigval_t si_value; /* Signal value */
int si_int; /* POSIX.1b signal */
void *si_ptr; /* POSIX.1b signal */
int si_overrun; /* Timer overrun count; POSIX.1b timers */
int si_timerid; /* Timer ID; POSIX.1b timers */
void *si_addr; /* Memory location which caused fault */
long si_band; /* Band event (was int in
glibc 2.3.2 and earlier) */
int si_fd; /* File descriptor */
short si_addr_lsb; /* Least significant bit of address
(since Linux 2.6.32) */
}
This would imply that you can send some additional info by choosing who (uid) you send the signal as and where from (pid -- you can tell if it is your child who's sending you the signal).
As for composing messages out of signal chains, that's theoretically possible, but you'd need to make sure your signal chain won't get randomly interrupted by another process (you can't prevent certain signal such as SIGKILL, but then, you're done when you receive a SIGKILL so no more translating message chains into ASCII or whatever :)
There's also sigqueue, which you can use to attach an integer to a signal you send (http://www.kernel.org/doc/man-pages/online/pages/man2/sigqueue.2.html), as I've learned in the following very good article on Linux signals:
http://www.kernel.org/doc/man-pages/online/pages/man2/sigqueue.2.html
Related
The MPI_Irecv and MPI_Isend operations return an MPI_Request that can be later marked as cancelled with MPI_Cancel. Is there a similar mechanism for blocking MPI_Probe and MPI_Mprobe ?
The context of the question is the latest implementation of Boost.MPI request handlers using Probe.
EDIT - Here is an example of how an hypothetical MPI_Probecancel could be used:
#include <mpi.h>
#include <chrono>
#include <future>
using namespace std::literals::chrono_literals;
// Executed in a thread
void async_cancel(MPI_Probe *probe)
{
std::this_thread::sleep_for(1s);
int res = MPI_Probecancel(probe);
}
int main(int argc, char* argv[])
{
int provided;
MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);
if (rank == 0)
{
// A handle to the probe (similar to a request)
MPI_Probe probe;
// Start a thread
// `probe` will be filled with the next call, pretty ugly
// Ideally, this should be done in two steps like MPI_Irecv, MPI_Wait
auto res = std::async(std::launch::async, &async_cancel, &probe);
MPI_Message message;
MPI_Status status;
MPI_MProbe(1, 123, MPI_COMM_WORLD, &message, &status, &probe);
if (!probe.cancelled)
{
int buffer;
MPI_Mrecv(&buffer, 1, MPI_INT, &message, &status);
}
}
else
std::this_thread::sleep_for(2s);
MPI_Finalize();
return 0;
}
First, the premise / nomenclature of your question is wrong. It is the nonblocking calls. MPI_Irecv and MPI_Isend which return a request object that you may cancel. For these calls, you cancel the local operation.
MPI_Probe and MPI_Mprobe are in fact blocking. You cannot possibly cancel these operations in the sense that control flow will only leave when a message is available.
On the other hand, MPI_Iprobe and MPI_Improbe are nonblocking, meaning they always complete immediately, telling you whether a message is available.
For neither kind of probe call, there is any kind of local state left after the completion. So there is nothing that could be cancelled locally after the functions return.
That said, if a probe tells you that a message is available, you should definitely receive it. Otherwise a send operation may bock and you would leak resources on all side. But that's just a receive operation.
Edit: Regarding your idea to cancel a ongoing local MPI_Probe in a concurrent thread: This is not directly supported.
Theoretically, you could emulate this on a conforming implementation with MPI_THREAD_MULTIPE by running the probe on MPI_ANY_SOURCE and send a message to the same rank from the other thread. That, of course, has the consequence that you change must probe on message from any incoming rank.
Realistically, if you have to do this, you would probably just use a loop like while(!cancelled) MPI_Iprobe();.
That said, I would again question the scenario: How would another thread on your rank suddenly know to cancel a local MPI_Probe operation? It would probably have to be based on information received from a remote rank - in which case that would be covered by actually being able to receive information from it, i.e. the actual Probe would complete.
Maybe for some high-level abstraction it makes some sense to offer a local cancel, but in an actual practical situation I would believe you could design a idiomatic pattern without needing this.
I have just started openCL C programming. All work items of a work group update unique locations of local memory. Later, a private variable of a work item is updated based on local data updated by two other work items. Something like this:
__kernel MyKernel(__global int *in_ptr)
{
/* Define a variable in private address space */
int priv_data;
/* Define two indices in private address space */
int index1, index2;
/* index1 and index2 are legitimate local work group indices */
index1 = SOME_CORRECT_VALUE;
index2 = ANOTHER_CORRECT_VALUE;
/* Define storage in local memory large enough to cater to all work items of this work group */
__local int tempPtr[WORK_GROUP_SIZE];
tempPtr[get_local_id(0)] = SOME_RANDOM_VALUE;
/* Do not proceed until the update of tempPtr by this WI has completed */
mem_fence(CLK_LOCAL_MEM_FENCE);
/* Do not proceed until all WI of this WG have updated tempPtr */
barrier(CLK_LOCAL_MEM_FENCE);
/* Update private data */
priv_data = tempPtr[index1] + tempPtr[index2];
}
Although the snippet above is conservative, wouldn't barrier have done the job as it internally does fencing?
Yes, barrier already does fencing.
A barrier will sync the execution in that point. So, all previous instructions have to be executed, therefore memory is consistent at that point.
A fence will only ensure all reads/writes are finished before any further read/write is performed, but the workers may be executing different instructions.
In some cases you can go with a single fencing. If you do not care about local workers going out of sync, and you just want the previous memory writes/read be completed. In your case a fence would be enough. (unless that code is running in a loop and there is extra code you have not put in the example).
I have a QT class instance, called C, (C inherits QOBJECT) that sends a signal S.
In my program, other QT classes instances X are created and destroyed when the program runs. These other classes connect and disconnect S, i.e. they run:
connect(C,SIGNAL(S()), this, SLOT(my_func())); // <this> is an instance of X
or
disconnect(C,SIGNAL(S()), this, SLOT(my_func()));
In class C, the calculation of whether S should be emitted (and the data associated to it - not shown here) is rather complicated, so I would like the instance of class C (which emits the signal) to be notified when one(or more) object are connected (listening) to S or when all are disconnected.
I have read about the connectNotify and disconnectNotify functions, but their usage is discouraged. Besides the documentation does not state very clearly if there is a one to one relationship between the number of (dis)connectNotify calls and the number of "listener" to the signal (or can one single connectNotify be called for more than one listener?).
Can I just count positively (count++) the number of connectNotify and negatively (count--) the number of disconnectNotify and just react to non-zero value?
Any better way to do this?
First, I think you've got it right that connectNotify and disconnectNotify can be used for this purpose - each connect event will be counted properly, even if it is a duplicate from the same object.
You can also double check this with QObject::receivers
int QObject::receivers ( const char * signal ) const [protected]
Returns the number of receivers connected to the signal. Since both
slots and signals can be used as receivers for signals, and the same
connections can be made many times, the number of receivers is the
same as the number of connections made from this signal. When calling
this function, you can use the SIGNAL() macro to pass a specific
signal: if (receivers(SIGNAL(valueChanged(QByteArray))) > 0) {
QByteArray data;
get_the_value(&data); // expensive operation
emit valueChanged(data); } As the code snippet above illustrates, you can use this function to avoid emitting a signal that
nobody listens to. Warning: This function violates the object-oriented
principle of modularity. However, it might be useful when you need to
perform expensive initialization only if something is connected to a
signal.
My suggestion would be to write a simple test program. Override connectNotify and disconnectNotify to increment/decrement a counter, but also use receivers to verify that the counter is correct. Try connecting multiple times, disconnecting multiple times, disconnecting even if there is no connection, etc.
Something to be careful of: connect and disconnect are thread-safe; I'm not sure if the matching Notify functions are safe also.
Since Qt 5.0, you can do this more easily with the QObject::isSignalConnected function. Example from the documentation:
static const QMetaMethod valueChangedSignal = QMetaMethod::fromSignal(&MyObject::valueChanged);
if (isSignalConnected(valueChangedSignal)) {
QByteArray data;
data = get_the_value(); // expensive operation
emit valueChanged(data);
}
I am looking for some sample code of a dead simple libevent-based TCP-Server which broadcasts incoming Messages to all connected clients. On the Web I only found TCP-Servers which echoes back messages.
One echo example if found is on the bottom of this page http://www.wangafu.net/~nickm/libevent-book/Ref8_listener.html
I am sure that its not so difficult to change the code provided on this Site, so that messages are brodcast to all connected clients, but I don't know how.
Could someone advise me?
EDIT: Yes, some kind of a chat server. It seams i need to do sth like this:
void server_read_cb(struct bufferevent *bev, void *data)
{
struct evbuffer *input = bufferevent_get_input(bev);
struct evbuffer *output = bufferevent_get_output(bev);
char *mem = malloc(len); /* XXX: check for malloc failure */
evbuffer_remove(input, mem, len);
"for every connection conn" {
/* XXX you'll need to implement a real connection list;
the above isn't real C. */
evbuffer_add(bufferevent_get_output(conn), mem, len);
}
free(mem);
}
But i can't put this to work.
Seems you want something similar to a chat server. One example is here. Basically, when you receive data from one connection, you just go through the list of connections and send that same data to each one (including/excluding the original).
When using a serial port via POSIX, it's recommended to save the original attributes using tcgetattr() before changing them with tcsetattr(), and then restore them before closing the port. What about when a program is terminated by pressing control-C or when the program receives SIGINT? I haven't seen this covered in any of the serial tutorials.
Apparently an atexit() function wouldn't be sufficient, because it's not called by the default SIGINT handler. So it seems installation of a signal handler would be necessary that restores the attributes to any serial ports still open. Is it even safe to call tcsetattr() from a signal handler?
One might simply dismiss this issue as insignificant, but it's common to terminate a program with control-C, especially one that can take tens of seconds to complete operations. If it's OK not to preserve serial port settings in this case, then there seems little reason to preserve them at all. If anything, it might be better not to bother, rather than do it inconsistently.
I found some examples of source code doing the above, but nothing well-documented. I guess I'm interested in some discussion of whether this is a good idea. Thanks.
After further research I think I've answered this to my satisfaction.
First, in the man page for signal I noticed that a signal handler is specifically allowed to call tcsetattr(), along with a few others:
The signal handler routine must be very careful, since processing elsewhere was interrupted at some arbitrary point. POSIX has the concept of "safe function". If a signal interrupts an unsafe function, and handler calls an unsafe function, then the behavior is undefined. Safe functions are listed explicitly in the various standards. The POSIX.1-2003 list is ... `raise()` ... `signal()` ... `tcsetattr()` [trimmed to relevant ones]
This strongly suggests that the POSIX committee had this exact kind of thing in mind, and leads to a straight forward approach where you change the SIGINT handler once you've opened serial and saved its attributes, then in your handler, restore them and the old SIGINT handler, then re-raise the signal:
static void (*prev_sigint)( int );
static termios saved_attr;
static int fd;
static void cleanup( int ignored )
{
tcsetattr( fd, TCSANOW, &saved_attr );
signal( SIGINT, prev_sigint );
raise( SIGINT );
}
int main( void )
{
open_serial_and_save_attrs();
prev_sigint = signal( SIGINT, cleanup );
...
}