Here is my code:
Code:
#include <stdio.h>
#include <netdb.h>
#include <string.h>
int
resolvehost(
const char* hostname,
char* hostent_buff,
int hostent_buff_len,
struct hostent **p_hp)
{
struct hostent hostbuf;
struct hostent *hp = *p_hp = NULL;
int herr = 0;
int hres = 0;
hres = gethostbyname_r(hostname, &hostbuf,
hostent_buff, hostent_buff_len, &hp, &herr);
if (NULL == hp)
{
fprintf(stderr, "gethostbyname_r() failed to resolve hostname [%s]", hostname);
return NO_ADDRESS;
}
*p_hp = hp;
return NETDB_SUCCESS;
}
int
mcc_sys_gethostbyname()
{
char buff[4096];
struct hostent *hp = NULL;
if( resolvehost("192linvm35", buff, sizeof(buff), &hp) != NETDB_SUCCESS )
return 1;
/*char buff2[4096];
struct hostent *hp2 = NULL;
if( resolvehost("192linvm35", buff2, sizeof(buff2), &hp2) != NETDB_SUCCESS )
return 1;*/
char** ips = hp->h_addr_list;
printf("%s : %s\n", hp->h_name, hp->h_aliases[0]);
while( *ips )
{
unsigned char* ipfields = *ips;
printf("%u.%u.%u.%u\n", ipfields[0], ipfields[1], ipfields[2], ipfields[3]);
++ips;
}
return 0;
}
#define NUM_THREADS 10
int main()
{
pthread_t threads[NUM_THREADS];
int j;
for( j=0; j < NUM_THREADS; j++ )
{
int ret = pthread_create(&threads[j],NULL,mcc_sys_gethostbyname,(void*)NULL);
if(ret == 0)
{
printf("**************Currently thread %d running*************\n",j);
}
}
for( j=0; j < NUM_THREADS; j++ )
{
int ret = pthread_join(threads[j], NULL);
if(ret ==0)
{
printf("*************thread %d going to stop************\n",j);
}
}
return (0);
}
I am compiling this code with below command:
gcc "filename" -g -o "executable name" -lpthread
And here is data race in helgrind report:
==6291== Possible data race during read of size 1 at 0x3989357f80 by thread #3
==6291== at 0x6E4D15E: _nss_files_gethostbyname_r (in /lib64/libnss_files-2.5.so)
==6291== by 0x39890EB5D3: gethostbyname_r@@GLIBC_2.2.5 (in /lib64/libc-2.5.so)
==6291== by 0x4006D0: resolvehost (gethostbyname_r.c:18)
==6291== by 0x400749: mcc_sys_gethostbyname (gethostbyname_r.c:38)
==6291== by 0x4A0B330: mythread_wrapper (hg_intercepts.c:201)
==6291== by 0x398A00683C: start_thread (in /lib64/libpthread-2.5.so)
==6291== by 0x39890D4FCC: clone (in /lib64/libc-2.5.so)
==6291== This conflicts with a previous write of size 8 by thread #2
==6291== at 0x398907A00A: memset (in /lib64/libc-2.5.so)
==6291== by 0x39890E3FD3: do_init (in /lib64/libc-2.5.so)
==6291== by 0x398A00C1D2: pthread_once (in /lib64/libpthread-2.5.so)
==6291== by 0x39890EB73D: gethostbyname_r@@GLIBC_2.2.5 (in /lib64/libc-2.5.so)
==6291== by 0x4006D0: resolvehost (gethostbyname_r.c:18)
==6291== by 0x400749: mcc_sys_gethostbyname (gethostbyname_r.c:38)
==6291== by 0x4A0B330: mythread_wrapper (hg_intercepts.c:201)
==6291== by 0x398A00683C: start_thread (in /lib64/libpthread-2.5.so)