I have this code:
#include <gtkmm.h>
#include <unistd.h>
void send_msg(Gtk::Entry* entry, int* fd);
Glib::ustring* receive_msg(int* fd);
bool handle_msg(Gtk::Label* lbl, int* fd);
int main()
{
pid_t pid = fork();
int fd[2];
pipe(fd);
Gtk::Main gtkmain;
Gtk::Window* win;
Glib::RefPtr<Gtk::Builder> builder;
if (pid > 0)
{
close(fd[1]);
builder = Gtk::Builder::create_from_file("parent.glade");
builder->get_widget("parentwin", win);
Gtk::Label* lbl;
builder->get_widget("label", lbl);
sigc::slot<bool> timer = sigc::bind(sigc::ptr_fun(&handle_msg), lbl, fd);
Glib::signal_timeout().connect(timer, 1000);
}
else if (pid == 0)
{
close(fd[0]);
builder = Gtk::Builder::create_from_file("child.glade");
builder->get_widget("childwin", win);
Gtk::Button* send;
Gtk::Entry* txt;
builder->get_widget("send", send);
builder->get_widget("msg", txt);
send->signal_clicked().connect(sigc::bind(sigc::ptr_fun(&send_msg), txt, fd));
}
Gtk::Main::run(*win);
return EXIT_SUCCESS;
}
void send_msg(Gtk::Entry* entry, int* fd)
{
Glib::ustring msg = entry->get_text();
const char* c_msg = msg.c_str();
int i = 0;
char* c = new char(0);
while (*c = c_msg[i++])
{
write(fd[1], c, 1);
}
}
Glib::ustring* receive_msg(int* fd)
{
Glib::ustring* msg = new Glib::ustring;
char* c = new char(0);
do
{
read(fd[0], c, 1);
msg->append(c);
} while (*c);
return msg;
}
bool handle_msg(Gtk::Label* lbl, int* fd)
{
Glib::ustring* msg;
msg = receive_msg(fd);
lbl->set_text(*msg);
// delete msg;
return true;
}
and it’s purpose is this:
The whole program works similar to a chat program, just not intended for that. The child process brings up a window with an Entry and a Button in it, to send the contents of Entry using a low level code that uses write() function, and the parent brings up a window with just a Label in it to display the data received at low level with read().
The exact functionality that I’m after I could achieve without gtkmm, but even when I write the read() and write() codes right before gtkmm parts under close() to test the functionality of read/write as a test to bypass function calls, it still won’t work.
The only possibility I can think of, is an incompatibility between unistd.h and gtkmm.h.
(and also I know the code is a bunch of dirt in writing, to some extent, but its a practice, forget that! 😉 )
Thanks so much for your helps 🙂
Your pipe-management code is wrong. You’re supposed to
pipe()before youfork(), to make sure both file descriptors are inherited into the child process. Read up on the documentation of these functions.Here is a quite dense tutorial on Unix programming, it’s clearly visible that
pipe()is more or less the first call made, before launching the child process.