state-threads
[Top] [All Lists]

Re: problem with unpredictable values of variable

To: Matthijs Sypkens Smit <matthijs@xxxxxxxxxxxxx>
Subject: Re: problem with unpredictable values of variable
From: "Gene Shekhtman" <genes@xxxxxxxxxxxxxxxxxxxxxx>
Date: Mon, 18 Sep 2000 12:51:48 -0700
Cc: state-threads@xxxxxxxxxxx
In-reply-to: Matthijs Sypkens Smit <matthijs@xxxxxxxxxxxxx> "problem with unpredictable values of variable" (Sep 18, 7:45pm)
References: <00091819452102.04770@helena>
Sender: owner-state-threads@xxxxxxxxxxx
On Sep 18,  7:45pm, Matthijs Sypkens Smit wrote:
> Subject: problem with unpredictable values of variable
>
....
>
> The problem is this:
> I've tried to modifiy the server example to be able to return inputted
> strings in uppercase. Herefor I changed handle_session(...) to look like
this:
> ---
> void handle_session(long srv_socket_index, st_netfd_t cli_nfd) {
>   char buf[512];
>
>   struct in_addr *from = st_netfd_getspecific(cli_nfd);
>
>   if (st_read(cli_nfd, buf, sizeof(buf), SEC2USEC(REQUEST_TIMEOUT)) < 0) {
>     err_sys_report(errfd, "WARN: can't read request from %s: st_read",
>                  inet_ntoa(*from));
>     return;
>   }
>
>   if (st_write(cli_nfd, to_uppercase(buf), strlen(buf), -1) == -1) {
>     err_sys_report(errfd, "WARN: can't write response to %s: st_write",
>                  inet_ntoa(*from));
>     return;
>   }
>
>   RQST_COUNT(srv_socket_index)++;
> }
> ---
> and added the function:
> ---
> char* to_uppercase(char *string) {
>       int i;
>
>       for (i = 0; string[i] != '\0'; i++)
>               string[i] = toupper(string[i]);
>
>       return string;
> }
> ---
>
> This seemed to work at first, but today I discovered that the array of
> characters `buf' sometimes later on contained text I had inputted earlier,
> but in uppercase. I suspect that I'm either making a dumb mistake or are
> totally missing some vital concept here.
>

Matthijs,

The st_read() function (just like read(2)) returns the number of
bytes read and doesn't do '\0'-termination.  If you want to manipulate
`buf' as a string, you need to terminate it yourself:

void handle_session(long srv_socket_index, st_netfd_t cli_nfd)
{
  char buf[512];
  int n;
  struct in_addr *from = st_netfd_getspecific(cli_nfd);

  if ((n = st_read(cli_nfd, buf, sizeof(buf), SEC2USEC(REQUEST_TIMEOUT))) < 0)
{
    err_sys_report(errfd, "WARN: can't read request from %s: st_read",
                   inet_ntoa(*from));
    return;
  }

  /* '\0'-terminate the buffer */
  buf[n] = '\0';

  if (st_write(cli_nfd, to_uppercase(buf), strlen(buf), -1) == -1) {
    err_sys_report(errfd, "WARN: can't write response to %s: st_write",
                   inet_ntoa(*from));
    return;
  }

  RQST_COUNT(srv_socket_index)++;
}


Hope it helps,
Gene

-- 
Gene Shekhtman                       genes@xxxxxxx
Internet Systems Engineering         650-933-8676
Silicon Graphics, Inc.


<Prev in Thread] Current Thread [Next in Thread>