linux下叉socketpair SOCK_DGRAM [英] linux fork socketpair sock_dgram
问题描述
我是新来socketpairs,我需要我的孩子每次从结构到parent.I传递信息被告知这可以使用SOCK_DGRAM做,但我不知道该怎么办它。我看着在互联网上但我找不到一个具体的example.Can请你告诉例如锄头,你可以传递给家长的结构做出来的2个整数和一个字符串可能吗?我只想一个例子,所以我能理解,我怎么能建立这种socketpair并通过it.Thank信息发送您
I'm new to socketpairs and I need my children each to pass information from a structure to the parent.I was told this can be done using SOCK_DGRAM but I don't know how to do it.I looked over the internet but i couldn't find a concrete example.Can you please show for example hoe can you pass to the parent a structure made out of 2 ints and a string maybe ?I just want an example so I can understand how I could build this kind of socketpair and send information through it.Thank you
推荐答案
如何以下内容:
int sockets[2];
if (socketpair(AF_INET, SOCK_DGRAM, 0, sockets) != -1)
{
int res = fork();
if (res == 0)
{
/* In child process */
/* We only need one socket, so close the other */
close(sockets[0]);
struct some_structure my_struct;
write(sockets[1], &my_struct, sizeof(my_struct));
/* All done */
exit(0);
}
else if (res > 0)
{
/* In parent process */
/* We only need one socket, so close the other */
close(sockets[1]);
struct some_structure my_struct;
read(sockets[0], &my_struct, sizeof(my_struct));
}
}
以上code不检查或处理,错误。它不能处理包含结构的指针,使用数组结构是好的,但。
The above code doesn't check for, or handle, errors. It can't handle structures containing pointers, structures using arrays are okay though.
这篇关于linux下叉socketpair SOCK_DGRAM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!