Domanda

my problem is that i need to run a pthread so i can listen a pipe, the thing is i have the pipes in a struc:

struct Pipefd {
    int tuberia1[2];
    int tuberia2[2];
};

this is the way i create the pthread:

intptr_t prueba = pf.tuberia2[0];
pthread_create(NULL,NULL, listenProcess,reinterpret_cast<void*>(prueba));

and here is the method i invoke:

void *listenProcess(void* x){

    int a = reinterpret_cast<intptr_t>(x);
    close(0);
    dup(a);

    string word;

    while(getline(cin,word)){

        cout << "Termino y llego: " << word << endl;

    }
}

it compile, but i get a segmentation fault, but i dont understand. im newby in c++, i already search alot and didnt found an answer to work, the "reinterpret_cast" is a workaround that i found to compile it without errors.

Thanks for your time, im sorry about my english, it is not my mother language, so any grammar error you point, its well recive.

È stato utile?

Soluzione

The POSIX threads API allows you to pass a generic void* for user data when your thread function is first called.

Since you already have the following structure defined:

struct Pipefd {
    int tuberia1[2];
    int tuberia2[2];
};

Rather than casting a single field of this structure to void* you might want to pass a pointer to the actual structure:

void* ppf = reinterpret_cast<void *>(&pf);
pthread_create(NULL,NULL, listenProcess,ppf);

Now, your modified thread function would look like this:

void *listenProcess(void* x){
    Pipefd* ppf = reinterpret_cast<Pipefd *>(x);
    close(0);

    dup(ppf->tuberia2 [0]);

    string word;

    while(getline(cin,word)){
        cout << "Termino y llego: " << word << endl;
    }
}

UPDATE:

You also had an invalid call to pthread_create (...), you must pass it a pointer to a pthread_t variable. This should fix your segmentation fault caused by calling pthread_create (...):

void*     ppf = reinterpret_cast<void *>(&pf);
pthread_t tid;
pthread_create(&tid,NULL, listenProcess,ppf);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top