linux socket sock_dgram,linux fork socketpair sock_dgram

问题

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

回答1:

How about the following:

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

}

}

The above code doesn't check for, or handle, errors. It can't handle structures containing pointers, structures using arrays are okay though.

回答2:

Assuming that your string is represented as a char* as in

struct data {

int i, j;

char *s;

};

you need to devise some serialization format, because sending a pointer won't work; the pointee is not passed so it won't point to anything useful in the receiver (the parent). A simple format would be to put the integers end-to-end, then directly append the string including its NUL terminator, so you'd get

int senddata(int fd, struct data const *d)

{

size_t msglen = 2 * sizeof(int) + strlen(d->s) + 1;

char *msg = malloc(msglen);

if (msg == NULL)

return -1;

((int *)msg)[0] = d->i;

((int *)msg)[1] = d->j;

strcpy(msg + 2 * sizeof(int), d->s);

ssize_t r = send(fd, msg, msglen, 0);

free(msg);

return r;

}

with a corresponding receive function for the parent. You might want to put some maximum length on the string, because the parent needs to know the size of the message in advance.

来源:https://stackoverflow.com/questions/14212377/linux-fork-socketpair-sock-dgram

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值