简体   繁体   中英

C thread: SEGFAULT when trying to read thread's return value

I need opnsrc() function to return the number of bytes it read. When I try running the code below, SEGFAULT is raised. GDB shows that the culprit is int *rvi = (int *) rvp; from opnsrc() . I intend rvp to store return value from opnthrd() . How to fix this problem? Thank you.

static char iobfr[512];

static void *
opnthrd(void *argp)
{
    memset(iobfr, '\0', 512);
    char *fname = (char *) argp;
    FILE *fp = fopen(fname, "r");
    if (!fp) {
        pthread_exit((void *) -1);
    }
    int i = 0;
    int c;
    for (c = fgetc(fp); c != EOF; c = fgetc(fp)) {
        iobfr[i++] = c;
    }
    iobfr[i] = '\0';
    fclose(fp);
    fp = NULL;
    pthread_exit((void *) i);   
}

static int
opnsrc(char *fnam)
{
    pthread_t thrd;
    void *rvp;
    int rc = pthread_create(&thrd, NULL, opnthrd, fnam);
    if (0 != rc) {
        return (-1);
    }
    rc = pthread_join(thrd, &rvp);
    if (0 != rc) {
        return (-1);
    }   
    if (!rvp) {
        return (-1);
    }
    int *rvi = (int *) rvp;
    return *rvi;
}

int main()
{
    int ccnt = opnsrc("/var/tmp/hello.pl");
    printf("%d bytes read\n", ccnt);
    return 0;
}

Here:

pthread_exit((void *) i);   

You pass the value (not address) of i as the thread return value. Then:

rc = pthread_join(thrd, &rvp);
int *rvi = (int *) rvp;

Now you have stored the value from i into rvp , but then you use it as a pointer. Which it isn't.

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