Reputation: 685
Working with fork
, pipe
and signal.h
signal handling. STDIN
is used to quickly simulate socket connection with a network server. Pseudocode:
struct message_t {
uint32_t length;
uint8_t *data;
};
int is_shutdown = 0;
void signal_handler(int) {
//set is_shutdown if SIGINT
}
int main() {
//initialize
pipe();
fork();
if (parent) {
while(!is_shutdown) {
//0. initialize variables, buffer, message_t
//1. read string of unknown length from STDIN (or socket) to a buffer
//2. malloc() message_t and fill it's fields
//3. write() message_t to pipe
//4. free() message_t
}
}
if (child) {
while(!is_shutdown) {
//0. initialize variables, message_t
//1. read() message_t: read length, malloc() buffer, read data
//2. execute command
//4. free() message_t
}
}
//close pipe
}
Several thing that confuse me:
close()
the pipe
in the signal handler?free()
the buffer after the write()
?is_shutdown
flag and interprocess communication. Am I understanding it right that parent and child do not share is_shutdown
as the same variable (they are copies) and change to the one would not change the other?is_shutdown
for both signal handler and main
? Any hidden details like in concurrency via multithreading?malloc()
on each iteration of the parent's while
loop would not be wise from a performance standpoint. But defining buffer that is "big enough" feels like a hack (what if someday it would not be big enough). Am I wrong?I am quite new to C and it's memory and resource management: switching from C++14 development for powerful Intel based server/desktops to C development for ~180MHz ARM embedded systems so I may be worried to much and forget some obvious things.
Upvotes: 0
Views: 134
Reputation: 140788
is_shutdown
.write
makes a copy. After write
returns, it is safe to reuse or deallocate the buffer. (Make sure to handle short writes, though.)is_shutdown
. Clean up in the parent
and child
blocks after the while loops terminate.is_shutdown
needs to be declared with type volatile sig_atomic_t
, and, for a simple program like this, it should not be written to by anything other than the signal handler. Also, the signal handler should not read its value, it should only set it. And depending on details of the code you haven't shown us, it may be appropriate to install the signal handler without using SA_RESTART
, so that it interrupts blocking system calls.pipe
to using socketpair
before you start testing abrupt disconnects, because socketpair
fds behave much more like real network sockets.Upvotes: 1