如何在两个进程之间用管道发送整数! [英] How to send integer with pipe between two processes!

查看:183
本文介绍了如何在两个进程之间用管道发送整数!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在POSIX系统中使用管道发送整数,但是write()函数正在发送字符串或字符数据.有什么方法可以通过管道发送整数吗?

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?

致谢

推荐答案

安全的方法是使用snprintfstrtol.

但是,如果您知道两个进程都是使用相同版本的编译器创建的(例如,它们是fork的同一可执行文件),则可以利用以下事实:可以读取或写入C中的任何内容作为char的数组:

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

这篇关于如何在两个进程之间用管道发送整数!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆