我正在尝试编写一个客户端程序,该程序将使用多个线程一次从服务器下载多个块的文件。在继续之前,我首先尝试仅使用一个线程成功下载文件,但我不断收到此重新声明错误。我已经声明了一个全局变量索引,并想在一个函数中更新它。
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define FILE_NAME "output.txt"
int index = 0;
FILE * file;
void * receiveChunk(void * arg){
int sockfd = 0;
char buffer[1024];
char request[128];
int status = -1;
char ** hostInfo = (char **) arg; //might need three stars
struct sockaddr_in serv_addr;
int port = atoi(*(hostInfo + 2));
int connection_status;
while(status != 0){
memset(&serv_addr, 0, sizeof(struct sockaddr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(*(hostInfo + 1));
serv_addr.sin_port = htons(port);
sockfd = socket(PF_INET,SOCK_STREAM,0);
connection_status = connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
if(connection_status == -1){
printf("Error connecting to socket\n");
}
file = fopen(FILE_NAME, "w");
sprintf(request, "%d", index);
send(sockfd, request, sizeof(request), 0);
index++;
recv(sockfd, &buffer, sizeof(buffer), 0);
fwrite(buffer, 1, status, file);
}
return NULL;
}
int main(int argc, int ** argv){
pthread_t thread_id;
pthread_create(&thread_id, NULL, &receiveChunk, argv);
pthread_join(thread_id, NULL);
return 0;
}
据我所知,我没有在任何一个函数中重新声明索引,我认为在 C 中你可以毫无问题地修改函数中的全局变量。如果这是一些明显的错误或误解,我深表歉意,但任何帮助将不胜感激。