简体   繁体   English

如何在两个进程之间发送带管道的整数!

[英]How to send integer with pipe between two processes!

I am trying to send an integer with pipe in a POSIX system but write() function is working for sending string or character data. 我试图在POSIX系统中发送带管道的整数,但write()函数用于发送字符串或字符数据。 Is there any way to send integer with a pipe? 有没有办法用管道发送整数?

Regards 问候

The safe way is to use snprintf and strtol . 安全的方法是使用snprintfstrtol

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 : 但如果你知道这两个过程是使用编译器的相同版本创建的(例如,他们是这同一个可执行fork ED),你可以采取这样的事实,在C什么都可以读取或写入阵列优势char

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

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

Either send a string containing the ASCII representation of integer eg, 12345679 , or send four bytes containing the binary representation of int, eg, 0x00 , 0xbc , 0x61 , 0x4f . 任一发送包含的整数例如,ASCII码表示形式的字符串12345679 ,或发送包含INT的二进制表示,例如,四个字节0x000xbc0x610x4f

In the first case, you will use a function such as atoi() to get the integer back. 在第一种情况下,您将使用诸如atoi()类的函数来获取整数。

Aschelpler的答案是正确的,但如果这可以在以后增长,我建议您使用某种简单的协议库,如Google的Protocol Buffers,或只使用JSON或XML和一些基本架构。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM