From: Bill Cunningham on 2 May 2010 12:53 #include "main.h" #include <sys/poll.h> static struct pollfd po[1]; static struct addrinfo ad, *p; static int sock, con; static char buf[1024] = "hello world"; int client(char *ip, char *port) { ad.ai_family = PF_INET; ad.ai_socktype = SOCK_STREAM; getaddrinfo(ip, port, &ad, &p); sock = socket(p->ai_family, p->ai_socktype, 0); fcntl(sock, F_SETFL, O_NONBLOCK); connect(sock, p->ai_addr, p->ai_addrlen); po[0].fd = sock; po[0].events = POLLOUT | POLLERR; con = poll(po, 2, 3500); if (con == 0) { puts("time out err"); return 1; } if (po[1].revents & POLLERR) { perror("poll error"); return -1; } if (po[1].revents & POLLOUT) { send(sock, buf, strlen(buf) + 1, 0); puts("success"); return 0; } send(sock, buf, strlen(buf) + 1, 0); puts("success"); return 0; } For some reason this code never makes it to the IF that allows for send. The last send send's correctly to the ip that I input. Should I use continues in those IFs that are above the one that sends? if (po[1].revents & POLLOUT) { send(sock, buf, strlen(buf) + 1, 0); puts("success"); return 0; The code never makes it to here. This is probably a C syntax question. Bill
From: Rainer Weikusat on 2 May 2010 13:01 "Bill Cunningham" <nospam(a)nspam.invalid> writes: [...] > static struct pollfd po[1]; This is the same as static struct pollfd po; [...] > if (po[1].revents & POLLERR) { > perror("poll error"); > return -1; > } > if (po[1].revents & POLLOUT) { > send(sock, buf, strlen(buf) + 1, 0); > puts("success"); > return 0; > } po[1] is the same as *(po + 1) which would access the second element of the array po. But your array has only one element.
From: Bill Cunningham on 2 May 2010 14:43 Rainer Weikusat wrote: > po[1] is the same as *(po + 1) which would access the second element > of the array po. But your array has only one element. Oh yeah that's it. I was thinking wrongly then about the IF's. Thanks. Bill
From: Bill Cunningham on 3 May 2010 14:27 > Rainer Weikusat wrote: > >> po[1] is the same as *(po + 1) which would access the second element >> of the array po. But your array has only one element. I changed the code to static struct pollfd *po; and renamed the arrays po[0] and re-compiled and got a smooth compilation. Bill
From: Rainer Weikusat on 3 May 2010 15:26
"Bill Cunningham" <nospam(a)nspam.invalid> writes: >> Rainer Weikusat wrote: >> >>> po[1] is the same as *(po + 1) which would access the second element >>> of the array po. But your array has only one element. > > I changed the code to static struct pollfd *po; > > and renamed the arrays po[0] and re-compiled and got a smooth > compilation. This should result in a segfault at runtime because you are now trying to derefences a null pointer. You need to declare a structure, not a pointer to a structure. And access the revents-member like this: po.revents NB: This is only true for a single struct pollfd, as in your example. |