Linux 如何在两个进程之间用管道发送整数!
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5237041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send integer with pipe between two processes!
提问by erogol
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?
我试图在 POSIX 系统中用管道发送一个整数,但write()
函数正在用于发送字符串或字符数据。有没有办法用管道发送整数?
Regards
问候
采纳答案by aschepler
The safe way is to use snprintf
and strtol
.
安全的方法是使用snprintf
和strtol
。
But if you know both processes were created using the same version of compiler (for example, they're the same executable which fork
ed), you can take advantage of the fact that anything in C can be read or written as an array of char
:
但是,如果您知道这两个进程都是使用相同版本的编译器创建的(例如,它们是同一个可执行文件 which fork
ed),您可以利用以下事实:C 中的任何内容都可以作为 数组读取或写入char
:
int n = something();
write(pipe_w, &n, sizeof(n));
int n;
read(pipe_r, &n, sizeof(n));
回答by mouviciel
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
.
要么发送一个包含整数的 ASCII 表示的字符串,例如,,12345679
要么发送包含 int 的二进制表示的四个字节,例如,0x00
, 0xbc
, 0x61
, 0x4f
。
In the first case, you will use a function such as atoi()
to get the integer back.
在第一种情况下,您将使用诸如atoi()
获取整数之类的函数。
回答by alecco
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 Buffersor just JSON or XML with some basic schema.
Aschelpler 的回答是正确的,但如果这是以后可以发展的东西,我建议您使用某种简单的协议库,例如 Google 的Protocol Buffers或仅使用具有一些基本架构的 JSON 或 XML。
回答by Raviraj Patil
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