我做了一個多線程服務器,它有一個全局指針,鏈接列表,在線程中我試圖插入一些數據,但該數據(我插入)不保留,是有可能在全局值不保留的線程中。我使用下面的代碼(這是一個簡單的版本。)全局變量不保留其線程值
struct node {
int cn; //
struct node *next;
};
/*GLOBAL VARIABLES*/
struct node *start; //Global pointer to Linked List
/* END */
int main(int argc, char *argv[]) {
start = (struct node *)malloc(sizeof(struct node));
start -> cn =0;
int pid;
/* Declaration of Server goes here */
printf("Server Running ...\n");
while (1) {
/* accepting socket*/
pid = fork();
if (pid < 0)
error("ERROR on fork");
if (pid == 0) {
close(serverSocket);
dostuff(childSocket,start);
exit(0);
}
else
close(childSocket);
}
return 0;
}
void dostuff (int sock, struct node *pointer){
returnStatus = read(sock, &requestToJoin, sizeof(int));
if (returnStatus < 0)
error("ERROR reading from socket");
else{
/* Insert Data to global Pointer */
}
}
該代碼中沒有線程。 – netcoder