我在通过管道 n Linux 发送整数或整数数组时遇到问题,首先我尝试发送整数,请看这段代码:
#include <unistd.h>
#include<iostream>
#include<cstdlib>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
int main()
{
int count = 10 ;
//cout <<"Enter a digit : ";
//cin >> count ;
cout<<"\n";
int pfd1[1];
pipe(pfd1);
int a=fork();
if(a==0)
{
close(pfd1[0]);
write(pfd1[1],&count,sizeof(count));
close(pfd1[1]);
exit(0);
}
else
{
wait(NULL);
int n =0;
close(pfd1[1]);
read(pfd1[0],&n ,sizeof(n));
close(pfd1[0]);
cout <<"N from parent = "<<n<<"\n\n";
}
return 0;
}
输出:
N from parent = 4
输出应该是 10
与声明的相同,但它给了我 4
,即使我取消注释注释代码以便用户输入一个数字,输出始终是 4
,而它应该是用户输入的数字。
这里有什么问题?如果我想发送整数数组怎么办?
最佳答案
您将超出数组边界,您应该将 pfd1
声明为
int pfd1[2];
关于c++ - 通过管道传递整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30310589/