How to send integer with pipe between two processe

2019-03-18 09:20发布

问题:

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

回答1:

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));


回答2:

Either send a string containing the ASCII representation of integer e.g., 12345679, or send four bytes containing the binary representation of int, e.g., 0x00, 0xbc, 0x61, 0x4f.

In the first case, you will use a function such as atoi() to get the integer back.



回答3:

Aschelpler's answer is right, but if this is something that can grow later I recommend you use some kind of simple protocol library like Google's Protocol Buffers or just JSON or XML with some basic schema.



回答4:

Below one works fine for writing to pipe and reading from pipe as:

stop_daemon =123;
res = write(cli_pipe_fd_wr, &stop_daemon, sizeof(stop_daemon));
....
res = read(pipe_fd_rd, buffer, sizeof(int));
memcpy(&stop_daemon,buffer,sizeof(int));
printf("CLI process read from res:%d status:%d\n", res, stop_daemon);

output:

CLI process read from res:4 status:123


标签: c linux ipc pipe