With the code below, I tried to do multithreading. The functions msg_1 and msg_2 should run in the background, and they should be called with 2 arguments. With conn_1 and conn_2. But that doesnt work. My compiler gave me this error:
/usr/bin/ld: /tmp/cc7J77SE.o: in function `main':
server.c:(.text+0x258): undefined reference to `pthread_create'
/usr/bin/ld: server.c:(.text+0x277): undefined reference to `pthread_create'
collect2: Error: ld returned 1 as exit-code
I cannot figure out what I did wrong. Can someone help me?
Sorce of the program:
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define PORT_CONN1 4444
#define PORT_CONN2 4445
char buf1[1024];
char buf2[1024];
struct arg_struct {
int arg1;
int arg2;
};
void *msg_1(void *arguments) {
struct arg_struct *args = arguments;
while(1) {
recv(args->arg1, &buf1, 1024, 0);
send(args->arg1, buf1, sizeof(buf1), 0);
}
}
void *msg_2(void *arguments) {
struct arg_struct *args = arguments;
while(1) {
recv(args->arg2, &buf2, 1024, 0);
send(args->arg1, buf2, sizeof(buf2), 0);
}
}
int main() {
int sockfd_1, sockfd_2, conn_1, conn_2;
struct sockaddr_in host_addr, client_addr;
socklen_t sin_size;
int recv_length=1, ok=1;
sockfd_1 = socket(PF_INET, SOCK_STREAM, 0);
sockfd_2 = socket(PF_INET, SOCK_STREAM, 0);
setsockopt(sockfd_1, SOL_SOCKET, SO_REUSEADDR, &ok, sizeof(int));
setsockopt(sockfd_2, SOL_SOCKET, SO_REUSEADDR, &ok, sizeof(int));
host_addr.sin_family = AF_INET;
host_addr.sin_port = htons(PORT_CONN1);
host_addr.sin_addr.s_addr = 0;
memset(&(host_addr.sin_zero), "\0", 8);
bind(sockfd_1, (struct sockaddr *)&host_addr, sizeof(struct sockaddr));
host_addr.sin_family = AF_INET;
host_addr.sin_port = htons(PORT_CONN2);
host_addr.sin_addr.s_addr = 0;
memset(&(host_addr.sin_zero), "\0", 8);
bind(sockfd_2, (struct sockaddr *)&host_addr, sizeof(struct sockaddr));
listen(sockfd_1, 5);
listen(sockfd_2, 5);
while(1) {
pthread_t thread1, thread2;
sin_size = sizeof(struct sockaddr_in);
conn_1 = accept(sockfd_1, (struct sockaddr *)&client_addr, &sin_size);
conn_2 = accept(sockfd_2, (struct sockaddr *)&client_addr, &sin_size);
struct arg_struct args;
args.arg1 = conn_1;
args.arg2 = conn_2;
pthread_create(&thread1, NULL, msg_1, (void *)&args);
pthread_create(&thread2, NULL, msg_2, (void *)&args);
pthread_exit(NULL);
close(conn_1);
close(conn_2);
}
}