Ejemplo n.º 1
0
int cinit_ipc_init(void)
{
   key_t k_tmp;

   /* to_server */
   k_tmp = ftok(__CINIT_MSGQ_PATHNAME, __CINIT_MSGQ_TO_SERVER);
   if(k_tmp == -1) {
      print_errno(__CINIT_MSG_MSGQ_FTOK);
      return 0;
   }
   __cinit_mq_in = msgget(k_tmp, __CINIT_MSGQ_PERMS | IPC_CREAT);
   if(__cinit_mq_in == -1) {
      print_errno(__CINIT_MSG_MSGQ_MSGGET);
      return 0;
   }

   k_tmp = ftok(__CINIT_MSGQ_PATHNAME, __CINIT_MSGQ_TO_CLIENT);
   if(k_tmp == -1) {
      print_errno(__CINIT_MSG_MSGQ_FTOK);
      return 0;
   }
   __cinit_mq_out = msgget(k_tmp, __CINIT_MSGQ_PERMS | IPC_CREAT);
   if(__cinit_mq_out == -1) {
      print_errno(__CINIT_MSG_MSGQ_MSGGET);
      return 0;
   }

   return 1;
}
Ejemplo n.º 2
0
Archivo: main.c Proyecto: Julow/ft_ls
void			*filenew(char *name, char *path, DIR *dir, t_args *args)
{
	t_file			*file;

	file = MAL1(t_file);
	file->stats = MAL1(struct stat);
	file->path = ft_stringnew();
	ft_stringadd(file->path, path);
	while (file->path->length > 1 &&
		file->path->content[file->path->length - 1] == '/')
		ft_stringrem(file->path, file->path->length - 1, 1);
	if (file->path->length > 0 && name[0] != '/' &&
		file->path->content[file->path->length - 1] != '/')
		ft_stringaddc(file->path, '/');
	ft_stringadd(file->path, name);
	file->dir = dir;
	file->name = NULL;
	if (FLAG(FLAG_STAT) && lstat(file->path->content, file->stats) < 0)
	{
		print_errno(name, errno);
		kill_file(file);
		return (NULL);
	}
	file->real = name;
	file->name = get_name(file, name, args);
	return ((void*)file);
}
Ejemplo n.º 3
0
bool ConnectorManager_Client::AddConnectorSocket(int fd, ConnectorID_t ConnectorID) {

	if(fd == INVALID_SOCKET)
	{
		WriteLog(KERN_ERR "ConnectorManager_Epoll::AddConnectorSocket(): Error ! fd==INVALID" );
		return false;
	}

	if( m_uFDSize >= m_uEventsMaxSize )
	{
		WriteLog(KERN_ERR
				"ConnectorManager_Epoll::AddConnectorSocket(): Error ! m_uFDSize(%d)>m_uEventsMaxSize(%d)",
				m_uFDSize,
				m_uEventsMaxSize
				);
		return false;
	}

	struct epoll_event ev;
	ev.data.u64 = ToUint64( (uint32_t)fd, (uint32_t)ConnectorID );
	ev.events = EPOLLIN | EPOLLET;

	if( 0 != epoll_ctl(m_Epollfd, EPOLL_CTL_ADD, fd, &ev) )
	{
		print_errno();
		return false;
	}

	m_uFDSize++;

	return true;
}
Ejemplo n.º 4
0
void main()
{

	char a = 'c';
	char *b= &a;
	print_errno(b);
}
Ejemplo n.º 5
0
int run_init_svc(char *cinit_svc)
{
   pid_t pid;

   /*
    * leave cinit alone 
    */
   pid = fork();

   if(pid == -1) {              /* err */
      print_errno(MSG_ERR_FORK);
      return 0;
   } else if(pid == 0) {        /* child */
      cinit_ipc_sclose();
      set_signals(ACT_CLIENT);

      if(!cinit_ipc_logon())
         _exit(1);

      /*
       * FIXME: open stderr, stdin, stdout to files / syslog / logable ?
       * IMPLEMENT PER SERVICE! 
       */

      run_svc(cinit_svc);

      _exit(0);                 /* nobody cares about us, so exit successfully
                                 * anyway */
   }
   /*
    * parent exits, we don't care about our children 
    */
   return 1;
}
Ejemplo n.º 6
0
bool dir_create(const char *p_dir)
{
  assert(p_dir);

  char tmp_dir[MAX_FILENAME];
  return_path(p_dir, "", tmp_dir, MAX_FILENAME);

  struct stat st;

  // Check the dir
  pprintfnl("Checking %s...",tmp_dir);
  if(stat(tmp_dir,&st) == -1 && errno == ENOENT) {
    pprintfnl("missing, try to create it...");
#ifdef WINDOWS
    if(mkdir(tmp_dir) != -1) {
#else  
    if(mkdir(tmp_dir,DEFAULT_DIR_MASK) != -1) {
#endif
      pprintf("ok");
      return(TRUE);
    } else {
      print_errno(TRUE);
      pprintf("failed");
      return(FALSE);
    }
  } else {
    pprintf("ok");
    return(TRUE);
  }
}
Ejemplo n.º 7
0
Archivo: app.c Proyecto: HARM67/ft_ls
void	check_invalide(t_app *app)
{
	DIR		*dirp;
	t_p_arg	*tmp;

	tmp = app->first_p_arg;
	while (tmp)
	{
		dirp = opendir(tmp->path);
		if (dirp == 0)
		{
			if (errno == 20)
			{
				tmp->type = 1;
				app->have_file = 1;
			}
			else
				print_errno(tmp);
		}
		else
		{
			app->have_dir = 1;
			closedir(dirp);
		}
		tmp = tmp->next;
	}
}
Ejemplo n.º 8
0
static int      check_path(char **tab, t_shell *shell)
{
  char          *path;
  char          sub_path[PWD_BUFFER_SIZE];
  int           index;

  path = get_env_value(ENV_PATH, shell->env);
  if (!path || !my_strlen(path))
    return (0);
  index = 0;
  do
  {
    get_sub_path(path, sub_path, &index);
    my_strncat(sub_path, tab[0], PWD_BUFFER_SIZE);
    if (access(sub_path, F_OK | X_OK | R_OK) == 0)
    {
      exec(tab, NULL, sub_path);
      return (1);
    }
    else if (errno != ENOENT)
    {
      print_errno(sub_path);
      return (1);
    }
  } while (index < my_strlen(path));
  return (0);
}
Ejemplo n.º 9
0
int main()
{
   if(kill(1, SIG_CINIT_HALT) == -1) {
      print_errno(MSG_HALT_KILL);
      return 1;
   }

   return 0;
}
Ejemplo n.º 10
0
int		destroy_tools(void)
{
  time_t const	tm = time(NULL);
  char		*const time_str = ctime(&tm);

  time_str[strlen(time_str) - 1] = 0;
  fprintf(g_log_fileptr, "%s: end of log.\n\n", time_str);
  if (fclose(g_log_fileptr) == SYSERR)
    return (print_errno("cannot close log file"));
  return (EXIT_SUCCESS);
}
Ejemplo n.º 11
0
int32 server_recv_block (SOCKET sd, char *buf, int32 len)
{
    fd_set readfds;
    
    FD_ZERO (&readfds);
    FD_SET (sd, &readfds);
    if (select (sd+1, &readfds, NULL, NULL, NULL) == SOCKET_ERROR) {
	print_errno ("server_recv_select");
	return -2;		/* Error */
    }
    return (server_recv_noblock (sd, buf, len));
}
Ejemplo n.º 12
0
/*
 * Prints the following to stderr:
 *
 * 1.	HT_FR fail code.
 *
 * 2.	Localized fail message retrieved from fr_fail_what.
 *
 * 3.	print_errno.
 */
enum HT_FR
print_err_fr (
	FILE * outlog,
	const enum HT_FR code
	)
{
	const char * msg = fr_fail_what(code);

	int rv		= fprintf(outlog, "[%d]: %s\n", (int)code, msg);
	rv		= rv < 0 ? rv : print_errno(outlog);

	return rv < 0 ? HT_FR_FAIL_IO_PRINT : HT_FR_SUCCESS;
}
Ejemplo n.º 13
0
/*
 * Await connection.  Return conn_sd if successful, INVALID_SOCKET otherwise.
 */
SOCKET server_await_conn ( void )
{
    struct sockaddr_in address;
    int32 address_len = sizeof (address);
    int32 flag;

    ERRLOG((stderr, "%s(%d): Listening at port %d\n", __FILE__, __LINE__, bindport));

    if ((conn_sd = accept (listen_sd, &address, &address_len)) == INVALID_SOCKET) {
	print_errno ("conn_accept");
	return INVALID_SOCKET;
    }

    /* Set socket to unbuffered mode (ie, execute sends immediately) */
    flag = 1;
    if (setsockopt(conn_sd, IPPROTO_TCP, TCP_NODELAY, (char *)(&flag), sizeof(flag)) ==
	SOCKET_ERROR) {
	print_errno ("socket_nodelay");
	server_close_conn (conn_sd);
	return INVALID_SOCKET;
    }

    /*
     * Set socket to nonblocking mode.
     */
    flag = 1;
    if (SOCKET_IOCTL (conn_sd, FIONBIO, &flag) == SOCKET_ERROR) {
	print_errno ("socket_noblock");
	server_close_conn (conn_sd);
	return INVALID_SOCKET;
    }

    ERRLOG ((stderr, "%s(%d): Connected >>>>>>>> %s at %s\n",
	     __FILE__, __LINE__, inet_ntoa (address.sin_addr), prt_ctime()));
    
    return conn_sd;
}
Ejemplo n.º 14
0
int main (int argc, char *argv[], char *envp[])
{
    int fd,bytes_read;
    char* buf=malloc(MAX_STRING);
  //  if(argc<=1 || argv[1]==NULL)
  // {
   //     printf("Please enter the file name properly \n");
  // }
    
    fd = open("x.txt",O_RDONLY);
    if(fd < 0)
    {
        print_errno(errno,"x.txt");
        return -1;
    }
    while((bytes_read=read(fd,buf,20))>0)
    {
       printf("%s",buf);
       lseek(fd,250,SEEK_END);
    }
   // lseek(fd,250,SEEK_SET);
  //  printf("\n \n Offset changed\n");
    while((bytes_read=read(fd,buf,100))>0)
    {
       printf("%s",buf);
       lseek(fd,250,SEEK_END);
    }   
    if(bytes_read<0)
    {
        printf("Some error have occured while reading \n");
        print_errno(errno,"read command");

    }
    close(fd);
    return 0;
}
Ejemplo n.º 15
0
/*
 * Prints the following to stderr:
 *
 * 1.	HT_FAIL_INVOC fail code.
 *
 * 2.	Localized fail message retrieved from fail_invoc_what.
 *
 * 3.	print_errno.
 */
static
enum HT_FR
print_err_fail_invoc (
	const enum HT_FAIL_INVOC code
	)
/*@globals fileSystem, stderr, errno@*/
/*@modifies fileSystem, stderr@*/
{
	const char * msg = fail_invoc_what(code);

	int rv		= fprintf(stderr, "[%d:%d]: %s\n",
			(int)HT_FR_FAIL_INVOC, (int)code, msg);
	rv		= rv < 0 ? rv : print_errno(stderr);

	return rv < 0 ? HT_FR_FAIL_IO_PRINT : HT_FR_SUCCESS;
}
Ejemplo n.º 16
0
static void     exec(char **tab, char **env, const char *full_path)
{
  pid_t         pid;

  pid = fork();
  if (pid == 0)
  {
    reset_signals_state();
    if (full_path != NULL)
      xexecve(full_path, tab, env);
    else
      xexecve(tab[0], tab, env);
    exit(EXIT_FAILURE);
  }
  else if (pid > 0)
    wait(NULL);
  else
    print_errno(tab[0]);
}
Ejemplo n.º 17
0
int32 server_send_block (SOCKET sd, char *buf, int32 len)
{
    int32 k, rem;
    
    rem = len;
    while (rem > 0) {
	if ((k = send (sd, buf, rem, 0)) == SOCKET_ERROR) {
	    if (SOCKET_ERRNO != SOCKET_WOULDBLOCK) {
		print_errno ("server_send_block");
		return -1;		/* Error */
	    }
	} else if (k == 0)
	    return (len-rem);		/* EOF??  Error */
	else {
	    buf += k;
	    rem -= k;
	}
    }
    return len;
}
Ejemplo n.º 18
0
int32 server_recv_noblock (SOCKET sd, char *buf, int32 len)
{
    int32 k;
    
    if ((k = recv (sd, buf, len, 0)) == SOCKET_ERROR) {
	if (SOCKET_ERRNO != SOCKET_WOULDBLOCK) {
	    print_errno ("server_recv_noblock");
	    return -2;		/* Error */
	} else
	    return 0;
    } else if (k == 0)
	return -1;		/* EOF */
    else {
	if (fp) {
	    fwrite (buf, sizeof(char), k, fp);
	    fflush (fp);
	}
	return k;
    }
}
Ejemplo n.º 19
0
int		my_trace(int err, char *type, char *fmt, ...)
{
  va_list	args;
  time_t	curr_time;
  char		*c_time_str;
  int		c;

  c = ((strcmp(type, ERR) == 0) ? 2 : 1);
  curr_time = time(NULL);
  c_time_str = ctime(&curr_time);
  c_time_str[strlen(c_time_str) - 1] = 0;
  fprintf((c == 1 ? stdout : stderr),"[%s] ", c_time_str);
  fflush((c == 1 ? stdout : stderr));
  print_type(c, type);
  va_start(args, fmt);
  vfprintf((c == 1 ? stdout : stderr), fmt, args);
  va_end(args);
  if (print_errno(c) == 0)
    fprintf((c == 1 ? stdout : stderr), "\n");
  return (err);
}
Ejemplo n.º 20
0
/*
 * Prints the following to stderr:
 *
 * 1.	HT_FAIL_RREADER fail code.
 *
 * 2.	Localized fail message retrieved from fail_rreader_what.
 *
 * 3.	Contents of line (unless it's NULL or empty).
 *
 * 4.	print_errno.
 */
static
enum HT_FR
print_err_fail_rreader (
	FILE * outlog,
	const enum HT_FAIL_RREADER	code,
/*@in@*/
/*@notnull@*/
	const struct ht_line * const	line
	)
/*@globals fileSystem, stderr, errno@*/
/*@modifies fileSystem, stderr, errno@*/
{
	const char *	msg = fail_rreader_what(code);

	int rv		= fprintf(outlog, "[%d:%d]: %s\n",
			(int)HT_FR_FAIL_INVOC, (int)code, msg);
	if (NULL != line && !ht_line_empty(line))
	{
		size_t i;
		for (i = 0; i < line->wordc; i++)
		{
			const char * const wrd = line->words[i].chars;
			if (strlen(wrd) < (size_t)1)
			{
				continue;
			}
			rv = rv < 0 ? rv : fprintf(outlog, "[%s]", wrd);
			if (i + 1 < line->wordc)
			{
				rv = rv < 0 ? rv : fputc(' ', outlog);
			}
		}
		rv		= rv < 0 ? rv : fputc('\n', outlog);
	}
	rv			= rv < 0 ? rv : print_errno(outlog);

	return rv < 0 ? HT_FR_FAIL_IO_PRINT : HT_FR_SUCCESS;
}
Ejemplo n.º 21
0
void            parse(char *cmd, t_shell *shell)
{
  char          **tab;

  tab = my_str_to_wordtab(cmd);
  if (tab[0])
  {
    if (check_builtins(tab, shell));
    else if (is_dir(tab[0]))
      print_double_msg(tab[0], "Is a directory");
    else if (tab[0][0] != '/' && check_path(tab, shell));
    else if (access(tab[0], F_OK | X_OK | R_OK) == 0)
      exec(tab, NULL, NULL);
    else
    {
      if (errno == ENOENT && tab[0][0] != '/')
        print_error_double_msg(tab[0], "command not found");
      else
        print_errno(tab[0]);
    }
  }
  free_tab(tab);
}
Ejemplo n.º 22
0
int cinit_build_argv(char *basename, struct ba_argv *bav)
{
   int tmp;
   int argc;
   char pathtmp[PATH_MAX + 1];
   char *sbuf = NULL;
   char *p;

   /*
    * sane values 
    */
   bav->argv = NULL;
   bav->envp = NULL;

   /***********************************************************************
    * Try to get realname (for links)
    */
   if((tmp = readlink(basename, pathtmp, PATH_MAX)) == -1) {
      /*
       * nothing there? 
       */
      if(errno == ENOENT) {
         return BA_E_NOTFOUND;
      }
      if(errno != EINVAL) {
         return BA_E_OTHER;
      }
      tmp = strlen(basename);
      strncpy(pathtmp, basename, tmp);
   }
   pathtmp[tmp] = '\0';
   ++tmp;                       /* the byte to add to memory for \0; neither
                                 * readlink nor strlen count the \0 */

   /***********************************************************************
    * prepare argv0
    */
   bav->argv = malloc(sizeof(char *));
   if(bav->argv == NULL)
      return BA_E_MEM;

   *bav->argv = malloc(tmp);
   if(*(bav->argv) == NULL)
      return BA_E_MEM;

   strncpy(*(bav->argv), pathtmp, tmp);

   /********************** read params *********************/
   /*
    * FIXME check bounds! 
    */
   strcpy(pathtmp, basename);
   strcat(pathtmp, C_PARAMS);
   /*
    * ORC_ERR_NONEXISTENT: Ok, have sbuf set to NULL ORC_OK: Ok, have a filled
    * buffer (perhaps NULL, too) other: Error, print errno 
    */
   tmp = openreadclose(pathtmp, &sbuf);

   if(tmp != ORC_ERR_NONEXISTENT && tmp != ORC_OK) {
      print_errno(pathtmp);
      return BA_E_PARAMS;
   }

   sbuf = strip_final_newline(sbuf);

   /***********************************************************************
    * Now split the string, converting \n to \0
    */
   argc = 1;                    /* argv0 */
   while(sbuf != NULL) {
      p = strchr(sbuf, '\n');
      bav->argv = realloc(bav->argv, sizeof(char *) * (argc + 1));

      if(bav->argv == NULL)
         return BA_E_MEM;
      bav->argv[argc] = sbuf;   /* here begins the current argument */

      if(p != NULL) {           /* found another \n */
         *p = '\0';
         sbuf = p + 1;
      } else {                  /* end of string */
         sbuf = NULL;
      }

      ++argc;
   }

   /************ close argv list **************/
   bav->argv = realloc(bav->argv, sizeof(char *) * (argc + 1));
   if(bav->argv == NULL)
      return BA_E_MEM;
   bav->argv[argc] = NULL;      /* terminate argv list */

   /********************** read environment *********************/
   strcpy(pathtmp, basename);
   strcat(pathtmp, C_ENV);

   tmp = argc = 0;
   sbuf = NULL;

   tmp = openreadclose(pathtmp, &sbuf);

   if(tmp != ORC_ERR_NONEXISTENT && tmp != ORC_OK) {
      print_errno(pathtmp);
      return BA_E_PARAMS;
   }

   sbuf = strip_final_newline(sbuf);

   /************** build environment string **************/
   argc = 0;
   while(sbuf != NULL) {
      p = strchr(sbuf, '\n');

      bav->envp = realloc(bav->envp, sizeof(char *) * (argc + 1));
      if(bav->envp == NULL)
         return BA_E_MEM;

      bav->envp[argc] = sbuf;

      /*
       * if we found \n 
       */
      if(p != NULL) {
         *p = '\0';
         sbuf = p + 1;
      } else {
         sbuf = NULL;
      }
      ++argc;
   }

   /************ close env list **************/
   bav->envp = realloc(bav->envp, sizeof(char *) * (argc + 1));
   if(bav->envp == NULL) {
      return BA_E_MEM;
   }
   bav->envp[argc] = NULL;

   return BA_OK;
}
Ejemplo n.º 23
0
/*
 * Initialize server; create socket on which to listen for connection request from
 * client.  This server can only have one client connected at any moment.
 * Return 0 if successful, -1 otherwise.
 */
int32 server_initialize (int32 port)
{
    struct sockaddr_in address;
    int32 length;
    
#ifdef WIN32
    if (win32_init () != 0) {
	fflush (stdout);
	fprintf (stderr, "%s(%d): win32_init failed\n", __FILE__, __LINE__);
	return -1;
    }
#endif

    /* Open a TCP socket */
    if ((listen_sd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
	print_errno ("create_socket");
#ifdef WIN32
	win32_end ();
#endif
	return -1;
    }
    
    /* Bind socket to input argument port, or to  */
    bindport = (uint16) port;
    memset ((char *) &address, 0, sizeof (address));
    address.sin_family		= AF_INET;
    address.sin_addr.s_addr	= htonl(INADDR_ANY);
    address.sin_port		= htons((u_short)bindport);
    if (bind(listen_sd, (struct sockaddr *)(&address), sizeof(address)) == SOCKET_ERROR) {
	print_errno ("bind failed");
	printf ("%s(%d): Trying any available port\n", __FILE__, __LINE__);
	
	memset ((char *) &address, 0, sizeof (address));
	address.sin_family	= AF_INET;
	address.sin_addr.s_addr	= htonl(INADDR_ANY);
	address.sin_port	= 0;
	
	if (bind (listen_sd, (struct sockaddr *)(&address), sizeof(address)) ==
	    SOCKET_ERROR) {
	    print_errno ("Couldn't bind to any port");
	    closesocket (listen_sd);
	    listen_sd = INVALID_SOCKET;
#ifdef WIN32
	    win32_end ();
#endif
	    return -1;
	}
	
	/* Extract bound port */
	length = sizeof(address);
	if (getsockname (listen_sd, (struct sockaddr *)(&address), &length) ==
	    SOCKET_ERROR) {
	    print_errno ("Couldn't get socket name");
	    closesocket (listen_sd);
	    listen_sd = INVALID_SOCKET;
#ifdef WIN32
	    win32_end ();
#endif
	    return -1;
	}

	bindport = address.sin_port;
    }

    /* Prepare to accept client connection request */
    if (listen(listen_sd, 1) == SOCKET_ERROR) {
	print_errno ("listen_socket");
	closesocket(listen_sd);
	listen_sd = INVALID_SOCKET;
#ifdef WIN32
	win32_end ();
#endif
	return -1;
    }
    
    return 0;
}
Ejemplo n.º 24
0
int main(int argc, char **argv)
{
   char *initdir = CINIT_INIT;  /* default init dir */

   /*
    * Is this really needed? pid_t cpid;
    * 
    * if(cpid != 1) { mini_printf(CINIT_VERSION,2); mini_printf(MSG_USAGE,2);
    * return 0; }
    */

   /* Bootup "logo" */
   mini_printf(MSG_BOOTING, 1); mini_printf(initdir, 1); mini_printf("\n", 1);

   /* Should we start a profile? */
   while(argc > 1) {
      if(!strncmp(PROFILE, argv[argc - 1], strlen(PROFILE))) {
         initdir = malloc(strlen(CINIT_SVCDIR) +
                          strlen(&argv[argc - 1][strlen(PROFILE)]) + 2);
         if(initdir == NULL) {
            panic();
         }
         strcpy(initdir, CINIT_SVCDIR);
         strcat(initdir, SLASH);
         strcat(initdir, &argv[argc - 1][strlen(PROFILE)]);
         break;
      }
      --argc;
   }

   /* no configuration? - panic! */
   if(chdir(initdir) == -1) {
      print_errno(initdir);
      panic();
   }

   /* initialize communication (IPC) */
   if(!cinit_ipc_init()) panic();

   /* Init signal handler */
   signal_init_map(sigstages, cinit_global_signals);
   set_signals(SIGSTAGE_DAEMON);

   /* build service dependency tree */
   if(!gen_svc_tree(initdir)) panic();

   /* unused now, free if allocated */
   if(strcmp(initdir, CINIT_INIT)) free(initdir);

   /* FIXME: what todo?
    * change to /, so applications have that as cwd, too Is that really
    * seneful? Does that help any application? If not, just for looking nice,
    * that's not a reason to enable it. if(chdir(SLASH) == -1) {
    * print_errno(SLASH); panic(); } 
    */

   /* the main startup routine */
   if(!tree_exec(deps_pending)) panic();

   /* listen to commands after startup */
   while(1) {
      /* react on service changes (=process exited) */
      if(svc_exited) svc_status_changed(deps_pending);

      /* handle the changes */
      if(deps_pending) svc_handle_pending(deps_pending);

      /* listen until we get a message or get interrupted */
      cinit_ipc_listen();

      /*
       * check dependency list: perhaps we need to restart something 
       */
      /*
       * implement in cinit-0.3pre14/5 
       */

      // tree_exec(deps_pending);
      // reuse tree_exec()?
      // if(dep) { svc_start() .. ?
   }

   return 0;
}
Ejemplo n.º 25
0
int check_add_deps(struct listitem *svc, int type)
{
   char buf[PATH_MAX + 1];
   char oldpath[PATH_MAX + 1];
   struct dirent *tdirent;
   struct dep *deps = NULL;
   struct listitem *new_svc;
   DIR *d_tmp;

   /* remember where we started */
   if(!getcwd(oldpath, PATH_MAX + 1)) {
      print_errno(MSG_GETCWD);
      return 0;
   }

   /* Create path */
   strncpy(buf, svc->abs_path, PATH_MAX+1);
   if(type == DEP_NEEDS) {
      if(!path_append(buf, C_NEEDS)) return 0;
   } else {
      if(!path_append(buf, C_WANTS)) return 0;
   }

   d_tmp = opendir(buf);
   if(d_tmp == NULL) {
      if(errno != ENOENT) {
         print_errno(buf);
         return 0;
      }
      return 1;                 /* it's fine when there's no dependencies */
   }

   if(chdir(buf) == -1) {       /* change to needs or wants */
      print_errno(buf);
      return 0;
   }

   while((tdirent = readdir(d_tmp)) != NULL) {
      if(*(tdirent->d_name) == '.') continue;              /* ignore .* */

      /*
       * skip non-working directories / broken links path_absolute reports
       * errors on failure 
       */
      if(!path_absolute(tdirent->d_name, buf, PATH_MAX + 1)) continue;

      /* 1. create the service we depend on 2. initialize its dependencies */
      if(!(new_svc = gen_svc_tree(buf))) return 0;

      /*
       * We need ALL dependencies, as we are called only once per service; no
       * need to test that first! And the other service CANNOT know anything
       * about us yet, so we always add us to its list. 
       */

      /*
       * Dependencies: - a.needs b; add b to the list of dependencies. -
       * a.needs b; add a to the list of needed by b. 1. check whether the
       * dependency already exists 2. otherwise add it 3. do it once for needs, 
       * once for needed_by 
       */

      /* create a dependency entry containing us */
      deps = dep_create(svc);
      if(!deps) return 0;

      if(type == DEP_NEEDS) {
         /* add us to the other service */
         dep_entry_add(&(new_svc->needed_by), deps);

         /* add other service to us */
         deps = dep_create(new_svc);
         if(!deps) return 0;
         dep_entry_add(&(svc->needs), deps);
      } else {
         /* add us to the other service */
         dep_entry_add(&(new_svc->wanted_by), deps);

         /* add other service to us */
         deps = dep_create(new_svc);
         if(!deps) return 0;
         dep_entry_add(&(svc->wants), deps);
      }
   }
   if(chdir(oldpath) == -1) {
      print_errno(buf);
      return 0;
   }
   closedir(d_tmp);

   return 1;
}
Ejemplo n.º 26
0
ipc_t ipc_create(const char* name, int owner) {

    int isInited = 0;
    struct Queue* queue;

    ipc_t conn = malloc(sizeof(struct ipc_t));

    sprintf(conn->name, "/arqvenger_%s", name);

    if ((conn->lock = sem_open(conn->name, O_CREAT | O_EXCL, 0666, 0)) == SEM_FAILED) {
        conn->lock = sem_open(conn->name, 0);
        if (conn->lock == SEM_FAILED) {
            print_errno("Failed adquiring named lock");
            return NULL;
        }

        sem_wait(conn->lock);
        isInited = 1;
    }

    conn->fd = shm_open(conn->name, O_CREAT | O_RDWR, 0666);
    if (conn->fd == -1) {
        print_errno("shm_open failed");

        sem_close(conn->lock);
        if (owner) {
            sem_unlink(conn->name);
        }
        free(conn);

        return NULL;
    }

    if (!isInited) {
        if (ftruncate(conn->fd, SHMEM_SIZE) == -1) {
            print_errno("Truncate failed");

            sem_close(conn->lock);
            if (owner) {
                sem_unlink(conn->name);
                shm_unlink(conn->name);
            }
            free(conn);
            return NULL;
        }
    }

    conn->queue = mmap(NULL, SHMEM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, conn->fd, 0);
    if (conn->queue == (void*) -1) {
        print_errno("mmap");

        sem_close(conn->lock);
        if (owner) {
            sem_unlink(conn->name);
            shm_unlink(conn->name);
        }

        free(conn);
        return NULL;
    }

    if (isInited) {
        sem_post(conn->lock);
        return conn;
    }

    queue = conn->queue;
    for (size_t i = 0; i < ENTRIES_PER_QUEUE; i++) {
        queue->index[i] = -1;
        queue->slots[i].len = 0;
    }

    queue->readWait = ipc_sem_create(0);
    queue->writeSem = ipc_sem_create(ENTRIES_PER_QUEUE);
    if (queue->readWait == -1 || queue->writeSem == -1) {
        print_errno("failed creating sems");
        sem_close(conn->lock);
        ipc_sem_destroy(queue->readWait);
        ipc_sem_destroy(queue->writeSem);

        munmap(conn->queue, SHMEM_SIZE);
        if (owner) {
            sem_unlink(conn->name);
            shm_unlink(conn->name);
        }
        free(conn);
        return NULL;
    }

    sem_post(conn->lock);

    return conn;
}