Question

I have the following situation:

A Fortran program calls (iso_c_binding) a function (written in C) that starts a server (socket functions) via the pthread_create function. This server is supposed to keep running (waiting for connections) until a certain variable is set to 1. The problem I have is that as soon as the function that starts the server returns (to the Fortran program) the server thread exits. I am not sure how to handle the situation (have the server socket running till it gets the signal to stop).

Kind regards

(Code added)

fortran program

...
FUNCTION run_server(ServerRuns) bind(c,name='run_server')
 use iso_c_binding
 import :: c_int
 integer(kind=c_int) :: run_server
 integer(kind=c_int), value :: ServerRuns
END FUNCTION run_server
...
fserver = run_server(ServerRuns)
...

c run server code

int run_server(int cservrun){

  int err;
  pthread_t tid[1];
  int i = 0;

  if (cservrun != 0){
   printf("[error] Process already running.\n");
   return -1;
  }else{

    err = pthread_create(&(tid[0]), NULL, (void *)&server, NULL);

    if (err != 0){
      printf("[error] Can't create \"server\" thread");
      return -1;  
    }else{
      printf("Server running\n");
      return 0;
    }
  }
}

c server code

int server(void){

 ...
 stop_serv = 0;

 while(stop_serv == 0){
   printf("Server loop\n");
   newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);

   if (newsockfd < 0){ 
     printf("[error] on accept");
     return -1; 
   } 

   bzero(buffer,SOB);
   n = read(newsockfd,buffer,SOB-1);
   if (n < 0){ 
     printf("[error] reading from socket");
     return -1;
   }

   printf("Message: _%s_\n",buffer);

   close(newsockfd);

 }

 close(sockfd);
 cservrun = 0; 

 return 0;
 }

If I add a while(1) loop after the "Server running" statement in the "c run server code" (before the return 0) the server stays alive and keeps reading messages. I have to say that I am not an expert neither in Fortran programming nor in C programming.

Était-ce utile?

La solution

I just found the solution. I did some changes in the Makefile and I found out that I really missed the -pthread option. It is really weird that there were no error messages and that the thread was created at all. Thank you very much for all of your help! I really appreciate it.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top