On 03/07/2012 07:27 AM, Jonathan Ben Avraham wrote:
> Hi linux-il colleagues,
> In >= 2.6.31 are there any conditions under which a write to a
> connected UDP socket can block? e.g. some change in routing or iface
> config after connect and before write? Has anyone encountered a
> concrete exampe of a write to a UDP socket that blocks? See test code
> below. That is, I am trying to demonstrate that I can get to a
> situation where UDP write in fact does block.
> Best regards,

A UDP (or, for that matter, TCP) socket will block under only one
situation that I'm aware of: if the send buffers are full. Use select to
test whether you can write to it, just like you would any other file
descriptor.

One area where this actually works is cellular modems. If you are
transmitting over your bandwidth, sooner or later the socket will block.

As for the program below: are you sure it doesn't block?

Shachar
>
>  - yba
>
>
> #include <stdio.h>
> #include <strings.h>
> #include <sys/socket.h>
> #include <sys/types.h>
> #include <netinet/in.h>
> #include <net/if.h>
> #include <stdlib.h>
> #include <errno.h>
>
>
> int main()
> {
>         int sd;
>         int rc;
>         struct ifreq interface;
>         struct sockaddr_in sin;
>         unsigned char buf[1024];
>         struct sockaddr_in  serveraddr;
>
>         if (0 > (sd = socket(AF_INET, SOCK_DGRAM, 0))) {
>                 printf("socket failed\n");
>                 exit(1);
>         }
>
>         sin.sin_family = AF_INET;
>         sin.sin_port = htons(0);
>         bzero(&(sin.sin_zero), 8);
>
>         sin.sin_addr.s_addr = INADDR_ANY;
>
>         if (-1 == bind(sd, (struct sockaddr *)&sin, sizeof(struct
> sockaddr_in))) {
>                 printf("bind to sd failed [%m]");
>                 return -1;
>         }
>
>
>         bzero(&serveraddr, sizeof(struct sockaddr_in));
>         serveraddr.sin_family = AF_INET;
>         serveraddr.sin_port = htons(80);
>         inet_pton(AF_INET, "1.0.1.2", &serveraddr.sin_addr);
>
>         if (0 > (rc = connect(sd, (const struct sockaddr*)&serveraddr,
> sizeof(serveraddr)))) {
>                 printf("connect failed [%m]");
>                 exit(1);
>         }
>
>         while ( 1 ) {
>                 if (0 > (rc = write(sd, buf, 1024))) {
>                         printf("write error [%m]\n");
>                 }
>                 else
>                         printf("wrote to socket [%d]\n", rc);
>         }
> }
>
>


-- 
Shachar Shemesh
Lingnu Open Source Consulting Ltd.
http://www.lingnu.com

_______________________________________________
Linux-il mailing list
[email protected]
http://mailman.cs.huji.ac.il/mailman/listinfo/linux-il

Reply via email to