Erros在使用pthread_create和pthread_detach时

时间:2015-03-27 15:25:24

标签: c multithreading pthreads server

我正在编写一个可以接收来自多个客户端的消息的服务器,因此我使用多线程但我遇到了一些警告和错误的问题,这些警告和错误不允许我的代码成功编译。我已经搜索过,但仍无法找到造成这些错误的原因。

以下是代码:

#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <stdlib.h>
#include <strings.h>

#define ADRRESS "127.0.0.1"
#define PORT 9999


void *receive_tcp(void *clientfd)
{
    char buffer1[7];
    //char *buffer2;
    int n, i;

    n = read(clientfd, buffer1, sizeof(buffer1));

    for(i=0;i<n;i++)
    {
        printf("%c", buffer1[i]);
    }
}

void main()
{
    int sock;
    struct sockaddr_in s1;
    char buffer1[7];
    int n, i;

    printf("A criar socket...\n");

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("Erro ao criar socket.\n");
        exit(1);
    }

    bzero(&s1, sizeof(s1));
    s1.sin_family = AF_INET;
    s1.sin_port = htons(PORT);
    s1.sin_addr.s_addr = INADDR_ANY;

    printf("A ligar ao socket...\n");

    if (bind(sock, (struct sockaddr*)&s1, sizeof(s1)) != 0)
    {
        printf("Erro ao ligar socket.\n");
        exit(1);
    }

    printf("A configurar socket...\n");

    if (listen(sock, 10) != 0)
    {
        printf("Erro ao configurar socket.\n");
        exit(1);
    }
    printf("A entrar no ciclo...\n");

    while(1)
    {
        int clientfd;
        struct sockaddr_in client_addr;
        int addrlen=sizeof(client_addr);

        pthread_t thread1;

        printf("À espera de uma nova ligação...\n");
        clientfd = accept(sock, (struct sockaddr*)&client_addr, &addrlen);
        /*n = read(clientfd, buffer1, sizeof(buffer1));

        for(i=0;i<n;i++)
        {
            printf("%c", buffer1[i]);
        }*/

        pthread_create(&thread1, 0, receive_tcp, clientfd);       
        pthread_detach(thread1);

    }
}

以下是错误:

serv.c: In function ‘main’:
serv.c:82:3: warning: passing argument 4 of ‘pthread_create’ makes pointer from integer without a cast [enabled by default]
   pthread_create(&thread1, 0, receive_tcp, clientfd);       
   ^
In file included from serv.c:6:0:
/usr/include/pthread.h:244:12: note: expected ‘void * __restrict__’ but argument is of type ‘int’
 extern int pthread_create (pthread_t *__restrict __newthread,
            ^
/tmp/ccxdvY86.o: In function `main':
serv.c:(.text+0x1fe): undefined reference to `pthread_create'
serv.c:(.text+0x20a): undefined reference to `pthread_detach'
collect2: error: ld returned 1 exit status

1 个答案:

答案 0 :(得分:0)

错误仅仅是因为您在编译程序时没有提供库引用。只需使用编译命令

添加-lpthread即可