Linux下undefined reference to ‘pthread_create’问题解决
在试用Linux 线程模块时,试用pthread_create 函数。
编译命令为 gcc main.c -o test
时,会出现如下错误
/usr/bin/ld: /tmp/ccAusWl8.o: in function `main':
05_concurrent_server_thread.c:(.text+0x44c): undefined reference to `pthread_create'
/usr/bin/ld: 05_concurrent_server_thread.c:(.text+0x468): undefined reference to `pthread_detach'
collect2: error: ld returned 1 exit status
问题的原因:pthread不是linux下的默认的库,也就是在链接的时候,无法找到phread库中该函数的入口地址,于是链接会失败。
解决:在gcc编译的时候,附加要加 -lpthread参数即可解决。
试用如下命令即可编译通过
gcc main.c -o test -lpthread
如下编译通过
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <pthread.h>
#define N 128
void handler(int sig){
wait(NULL);
}
typedef struct{
struct sockaddr_in addr;
int acceptfd;
}MSG;
void *pthread_fun(void *arg){
int count = 0;
ssize_t bytes;
MSG msg = *(MSG *)arg;
char buf[N] = "666";
char text[N] = "";
while(1){
// 打印客户端信息
printf("ip:%s, port:%d\n", inet_ntoa(msg.addr.sin_addr), ntohs(msg.addr.sin_port));
// 接收数据
if((count = recv(msg.acceptfd,text,N,0))==-1){
perror("fail to recv");
exit(1);
}else if(count == 0){
printf("The client quited\n");
pthread_exit(NULL);
}
printf("from client: ");
for(int j=0;j<count;j++){
printf("%c",text[j]);
}
printf("\n");
//发送buf数据
if(send(msg.acceptfd,buf,sizeof(buf),0)==-1){
perror("fail to send");
exit(1);
}
}
}
int main(int argc, char const * argv[]){
if(argc < 3){
fprintf(stderr, "server Usage:%s ip port\n",argv[0]);
exit(1);
}
int sockfd;
// 创建tcp套接字
if((sockfd=socket(AF_INET,SOCK_STREAM,0)) == -1){
perror("fail to socket");
exit(1);
}
struct sockaddr_in serveraddr;
socklen_t addrlen = sizeof(serveraddr);
serveraddr.sin_family = AF_INET; // 协议族 AF_INET:ipv4网络协议
// inet_addr: 将点分十进制字符串ip地址转为整形数据
serveraddr.sin_addr.s_addr = inet_addr(argv[1]); // ip地址
// atoi 将数字型字符串转换为整形数据
// htons 将主机字节序转化为网络字节序
serveraddr.sin_port = htons(atoi(argv[2]));
// 将套接字和网络信息绑定
if(bind(sockfd,(struct sockaddr*)&serveraddr, addrlen) == -1){
perror("fail to connect");
exit(1);
};
// 将套接字设置为监听状态
if(listen(sockfd,5) == -1){
perror("fail to listen");
exit(1);
}
struct sockaddr_in clientsock;
addrlen = sizeof(clientsock);
printf("准备阻塞...\n");
// 使用信号,异步的方式处理僵尸进程
signal(SIGCHLD,handler);
while(1){
// 阻塞等待客户端的链接
int clisock = accept(sockfd,(struct sockaddr*)&clientsock, &addrlen);
// 创建子线程与客户端通信
MSG msg;
msg.addr = clientsock;
msg.acceptfd = clisock;
pthread_t thread;
if(pthread_create(&thread,NULL,pthread_fun,&msg)!=0){
perror("fail to pthread_create");
}
pthread_detach(thread);
}
// 关闭套接字描述符
//close(clisock);
//close(sockfd);
return 0;
}