How to send integer with pipe between two processes!

erogol picture erogol · Mar 8, 2011 · Viewed 33.9k times · Source

I am trying to send an integer with pipe in a POSIX system but write() function is working for sending string or character data. Is there any way to send integer with a pipe?

Regards

Answer

aschepler picture aschepler · Mar 8, 2011

The safe way is to use snprintf and strtol.

But if you know both processes were created using the same version of compiler (for example, they're the same executable which forked), you can take advantage of the fact that anything in C can be read or written as an array of char:

int n = something();
write(pipe_w, &n, sizeof(n));

int n;
read(pipe_r, &n, sizeof(n));