Medardas
Medardas

Reputation: 540

how to stop read() function?

I am writing an UDP client/server programs in C on linux. The thing is that I must add connection check feature. in linux man pages i found example of udp client with this feature( http://www.kernel.org/doc/man-pages/online/pages/man3/getaddrinfo.3.html ). It uses write/read functions to check server response. I tried to apply it to my program, and it looks like this:

char *test = "test";
nlen = strlen(test) + 1;
if (write(sock, test, nlen) != nlen) {              // socket with the connection
    fprintf(stderr, "partial/failed write\n");
    exit(EXIT_FAILURE);
}

nread = read(sock, buf, nlen);
if (nread == -1) {
    perror("Connection");
    exit(EXIT_FAILURE);
}

the problem is than than i execute program with this bit when server is on, it does nothing except reading input infinite time which it doesn't use too. I tried kill(getpid(), SIGHUP) interrupt, which i found other similar topic here, and shutdown(sock, 1), but nothing seems to work. Could you please tell me a way out how to stop the input read or any other possible option to check if udp server is active?

Upvotes: 0

Views: 292

Answers (1)

kcsoft
kcsoft

Reputation: 2947

You should use asynchronous reading.

For this you must use the select() function from "sys/socket.h".

The function monitors the socket descriptor for changes without blocking.

You can find the reference for it here or here or by typing "man select" in your console.

There is an example here for Windows, but its usage is very similar to UNIX.

Upvotes: 1

Related Questions