C++ – How do I read long from a pipeline?

How do I read long from a pipeline?… here is a solution to the problem.

How do I read long from a pipeline?

This involves unnamed pipes in interprocess communication.
I have a pipeline where one process stores a value and another process wants to read this value, int or long.

It is well described here http://tldp.org/LDP/lpg/node11.html how to create a pipeline in C. My question is how to read long or int from the pipe.

Excerpt from the above page:

/* Read in a string from the pipe */
int nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);

Well, in

general, I don’t know how pipes are handled in C (it’s like a file?). and how I read data other than a string from it.

Solution

You can’t “really” read a long from a pipe. You read a sequence of bytes from the pipe, and if you can define some protocol to represent the long that the bytes represent, you read a long.

Assuming that both ends of the pipeline use the same storage representation for long, if they were compiled for the same architecture using the same compiler, or for that matter different compilers but using the same ABI, then you can write (fd, &src_long, sizeof(long)) on one side; , then read(fd, &dst_long, sizeof(long)); At the other end. Add or subtract the usual confusion of making sure I/O is not done ahead of time.

Related Problems and Solutions