zidanow
zidanow

Reputation: 700

bad use of pthread, for waiting response of sockets

my main function is like this :

void create_serv_and_init_client(client_t *cl)
{
    static int i = 0;
    pthread_t thread_serv;
    serv_t serv;

    if (i == 0) {
        //cl[0].content = retrieve_info();
        cl[0].connected = 1;
        //PORT = cl[0].content.port;
        serv = create_serv_socket();
        if (pthread_create(&thread_serv, NULL, waiting_connection, \
        (void *)&serv) < 0) {
            perror("could not create thread");
            exit(1);
        }
        cl[0] = create_client(0);
        printf("OK\n");
        i++;

    }
}

and the waiting function of the pthread :

void *waiting_connection(void *server)
{
    serv_t *serv = (serv_t *)server;

    serv->newSocket = accept(serv->sockfd, (struct sockaddr*)&serv->newAddr, \
    &serv->addr_size);
    if (serv->newSocket < 0) {
        exit(1);
    }
    if ((serv->childpid = fork()) == 0) {
        close(serv->sockfd);
        while (recv(serv->newSocket, serv->buffer, 1024, 0) != 0) {
            printf("Client: %s\n", serv->buffer);
            send(serv->newSocket, serv->buffer, strlen(serv->buffer), 0);
            bzero(serv->buffer, sizeof(serv->buffer));
        }
    }

if i comment the pthread_create call and call after the if the waiting_connection function, it will work, so i have a problem with my pthread, but why he doesnt work ? thanks again !

Upvotes: 0

Views: 68

Answers (2)

Note a multi-threaded program can really only fork to execute a new program using execve. For example from Linux manuals:

  • After a fork() in a multithreaded program, the child can safely call only async-signal-safe functions (see signal-safety(7)) until such time as it calls execve(2).

printf for example can lock the stdout. If you happen to fork in while the printf lock is held by another thread then crazy things might or might not happen.

Upvotes: 0

jmq
jmq

Reputation: 1591

You may have a race condition which may cause undefined behavior. In create_serv_and_init_client() you define a local variable serv. The address of this variable is passed to the thread. When create_serv_and_init_client completes serv will go out of scope, even if the thread is still using it. As a result the value of serv may no longer be correct.

Upvotes: 2

Related Questions