简体   繁体   中英

C pthreads error

Programming Language C
below is the code that uses multiple threads to print out a file. There are no errors, however the code doesn't work correctly. However, when compiled it shows this warning 5 times: 'cast from pointer to integer of different size'

I've tried everything I can think of to resolve this issue, but haven't been success and now are just shooting in the dark. Does anyone see where my mistake is? Any help is greatly appreciated and will gladly provide any other information upon request.

Thanks.

#include <sys/mman.h>
#include <sys/stat.h> 
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#define NUM_THREAD 4


struct fileParams {
     int fd;
     int size;
};

void *printFile(void *stuff)
{
     struct fileParams *params = stuff;      
     int addr;
     addr=(unsigned char *)mmap(NULL, (int) &params->size, PROT_READ, 
     MAP_PRIVATE,(int) &params->fd,0);
     write(STDOUT_FILENO, addr, (int)&params->size);
}

int main (int argc, char * argv[])
{
     pthread_t threads[NUM_THREAD];
     unsigned char *addr;
     int fd,rc;
     struct stat sb;
     int numCPU=sysconf(_SC_NPROCESSORS_ONLN);
     struct fileParams params;  

     printf("Number of aviable cores: %d\n",numCPU);
     printf("Using 4 processors\n");

     if (argc != 2 || strcmp(argv[1], "—help") == 0)
          printf("Usage: %s file\n", argv[0]);

     fd=open(argv[1],O_RDONLY);
     if (fd == -1)
     {
         printf("File open fdailed.\n");
    exit(EXIT_FAILURE);
     }

    if (fstat(fd, &sb) == -1)
    {
        printf ("fstat error\n");
        exit(EXIT_FAILURE);
    }
    params.fd=fd;
    params.size=sb.st_size/4;
    for (int n = 0; n<4; n++)
         rc=pthread_create(&threads[n],NULL,printFile,&params);

    exit(EXIT_SUCCESS);
    }

You need provide inputs to functions that match the function - passing pointers where integers are wanted (or the other way around) will generate warnings or errors depending on compile options.

mmap takes an size_t as the 2nd parameter, but you are giving it a cast int to a pointer (&params->size), the same with mmaps 5th parameter.

Get rid of the '&' so it is just a int.

mmap also returns a void *, which you are then assigning to addr (an int).

Change int to a void * pointer type which should also fix the 5th warning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM