Exemple #1
0
int main(int argc, char **argv)
{
    int c = 0;
    int become_daemon = 1;
    int config_loaded = 0;
    config_t config;
    char *pidfile = NULL;

    opterr = 0;
    while ((c = getopt(argc, argv, "sc:p:")) != -1) {
        switch (c) {
            case 's':
                become_daemon = 0;
                break;
            case 'c':
                loadConfig(&config, optarg);
                config_loaded = 1;
                break;
            case 'p':
                pidfile = malloc(strlen(optarg) + 1);
                strcpy(pidfile, optarg);
                break;
            case 'h':
                printUsage();
                exit(0);
                break;
            case '?':
                printUsage();
                exit(EXIT_FAILURE);
                break;
            default:
                exit(EXIT_FAILURE);
        }
    }

    if (signal(SIGTERM, catch_signal) == SIG_ERR) {
        logError("Error while setting SIGTERM handler.\n");
        exit(EXIT_FAILURE);
    }

    if (become_daemon) {
        becomeDaemon();
    }

    if (pidfile != NULL) {
        writePID(pidfile);
        free(pidfile);
        pidfile = NULL;
    }


    if (!config_loaded) {
        loadConfig(&config, DEFAULT_CONFIG);
    }

    monitor(&config);

    exit(EXIT_SUCCESS);
}
int
main(int argc, char *argv[])
{
    int lfd, cfd;               /* Listening and connected sockets */
    struct sigaction sa;

    /* The "-i" option means we were invoked from inetd(8), so that
       all we need to do is handle the connection on STDIN_FILENO */

    if (argc > 1 && strcmp(argv[1], "-i") == 0) {
        handleRequest(STDIN_FILENO);
        exit(EXIT_SUCCESS);
    }

    if (becomeDaemon(0) == -1)
        errExit("becomeDaemon");

    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    sa.sa_handler = grimReaper;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        syslog(LOG_ERR, "Error from sigaction(): %s", strerror(errno));
        exit(EXIT_FAILURE);
    }

    lfd = inetListen(SERVICE, 10, NULL);
    if (lfd == -1) {
        syslog(LOG_ERR, "Could not create server socket (%s)", strerror(errno));
        exit(EXIT_FAILURE);
    }

    for (;;) {
        cfd = accept(lfd, NULL, 0);     /* Wait for connection */
        if (cfd == -1) {
            syslog(LOG_ERR, "Failure in accept(): %s",
                    strerror(errno));
            continue;           /* Try next */
        }

        switch (fork()) {       /* Create child for each client */
        case -1:
            syslog(LOG_ERR, "Can't create child (%s)",
                    strerror(errno));
            close(cfd);         /* Give up on this client */
            break;              /* May be temporary; try next client */

        case 0:                 /* Child */
            close(lfd);         /* Don't need copy of listening socket */
            handleRequest(cfd);
            _exit(EXIT_SUCCESS);

        default:                /* Parent */
            close(cfd);         /* Don't need copy of connected socket */
            break;              /* Loop to accept next connection */
        }
    }
}
int
main(int argc, char *argv[])
{
    becomeDaemon(0);

    /* Normally a daemon would live forever; we just sleep for a while */

    sleep((argc > 1) ? getInt(argv[1], GN_GT_0, "sleep-time") : 20);

    exit(EXIT_SUCCESS);
}
Exemple #4
0
int
main(int argc, char *argv[])
{
    int lfd, cfd;               /* Listening and connected sockets */
    struct sigaction sa;

    if (becomeDaemon(0) == -1)
        errExit("becomeDaemon");

    /* Establish SIGCHLD handler to reap terminated child processes */

    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    sa.sa_handler = grimReaper;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        syslog(LOG_ERR, "Error from sigaction(): %s", strerror(errno));
        exit(EXIT_FAILURE);
    }

    lfd = inetListen(SERVICE, 10, NULL);
    if (lfd == -1) {
        syslog(LOG_ERR, "Could not create server socket (%s)", strerror(errno));
        exit(EXIT_FAILURE);
    }

    for (;;) {
        cfd = accept(lfd, NULL, NULL);  /* Wait for connection */
        if (cfd == -1) {
            syslog(LOG_ERR, "Failure in accept(): %s", strerror(errno));
            exit(EXIT_FAILURE);
        }

        /* Handle each client request in a new child process */

        switch (fork()) {
        case -1:
            syslog(LOG_ERR, "Can't create child (%s)", strerror(errno));
            close(cfd);                 /* Give up on this client */
            break;                      /* May be temporary; try next client */

        case 0:                         /* Child */
            close(lfd);                 /* Unneeded copy of listening socket */
            handleRequest(cfd);
            _exit(EXIT_SUCCESS);

        default:                        /* Parent */
            close(cfd);                 /* Unneeded copy of connected socket */
            break;                      /* Loop to accept next connection */
        }
    }
}
int main( int argc, char *argv[] )
{
	#if 0
	if ( argc != 3 ){
		fprintf ( stderr, "usage: $ %s <device> <text>\n", argv[0] );
		fprintf ( stderr, "\t like: $ %s /dev/ttyS0 \"this content will show on termial of /dev/ttyS0\"\n", argv[0]);
		exit(219);
	}
	#else
	if ( argc < 2 ){
		fprintf ( stderr, "usage: $ %s <TTY device> [option...]\n", argv[0] );
		fprintf ( stderr, "\t like: $ %s /dev/ttyS0\n", argv[0]);
		fprintf ( stderr, "\n\t [Option...]: Enter the path which is CGIDebugLogd.py file exist on. \n" 
						  "\t this program will default open CGIDebugLogd.py on the same PATH with \"%s\"! \n\n", argv[0]);
		exit(CMD_ERR);
	}
	#endif


		char   *ptr=NULL;
		size_t size;
	
		ptr = path_alloc(&size);                         /* APUE funciton. */
		if (getcwd(ptr, size) == NULL){
			fprintf ( stderr, "getcwd() failed!\n");
			exit(BUILDIN_FUNC_ERR);
		}

	if (doDebug){
		fprintf (stdout, "cwd = %s\n", /*current work path*/ptr);
	}

	char PathArray[256] = {'\0'};
	snprintf(PathArray, 256, "%s", argv[0] );
	getCMDPath(PathArray, 256);

	char absolutePath[512] = {'\0'};
	snprintf(absolutePath, 512, "%s%s", ptr, PathArray );
	free(ptr);

	becomeDaemon(0);

	//run(argc, argv);
	run(argc, argv, absolutePath);

	exit(0);
}
int
main(int argc, char *argv[])
{
    const int SLEEP_TIME = 15;      /* Time to sleep between messages */
    int count = 0;                  /* Number of completed SLEEP_TIME intervals */
    int unslept;                    /* Time remaining in sleep interval */
    struct sigaction sa;

    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    sa.sa_handler = sighupHandler;
    if (sigaction(SIGHUP, &sa, NULL) == -1)
        errExit("sigaction");

    if (becomeDaemon(0) == -1)
        errExit("becomeDaemon");

    logOpen(LOG_FILE);
    readConfigFile(CONFIG_FILE);

    unslept = SLEEP_TIME;

    for (;;) {
        unslept = sleep(unslept);       /* Returns > 0 if interrupted */

        if (hupReceived) {              /* If we got SIGHUP... */
            hupReceived = 0;            /* Get ready for next SIGHUP */
            logClose();
            logOpen(LOG_FILE);
            readConfigFile(CONFIG_FILE);
        }

        if (unslept == 0) {             /* On completed interval */
            count++;
            logMessage("Main: %d", count);
            unslept = SLEEP_TIME;       /* Reset interval */
        }
    }
}
Exemple #7
0
int main(int argc, char* argv[]){
	const int SLEEP_TIME=15;
	int count=0;
	int unslept;

	struct sigaction sa;
	sigemptyset(&sa.sa_mask);
	//sa.sa_flags=SA_RESTART;
	sa.sa_flags=SA_NOCLDSTOP;
	sa.sa_handler=sighupHandler;
	if(sigaction(SIGHUP,&sa,NULL)==-1){
		perror("error sigation");
	}
	if(becomeDaemon(0)==-1){
		perror("error becomeDaemon");
	}

	logOpen(LOG_FILE);
	readConfigFile(CONFIG_FILE);

	unslept=SLEEP_TIME;

	for(;;){
		unslept=sleep(unslept);
		if(hupReceived){
			hupReceived=0;
			logClose();
			logOpen(LOG_FILE);
			readConfigFile(CONFIG_FILE);
		}
		if(unslept==0){
			count++;
			logMessage("Main: %d", count);
			unslept=SLEEP_TIME;	
		}
	}
	return 0;
}
int
main(int argc, char *argv[])
{
    int sfd;
    ssize_t numRead;
    socklen_t len;
    struct sockaddr_storage claddr;
    char buf[BUF_SIZE];
    char addrStr[IS_ADDR_STR_LEN];

    if (becomeDaemon(0) == -1)
        errExit("becomeDaemon");

    sfd = inetBind(SERVICE, SOCK_DGRAM, NULL);
    if (sfd == -1) {
        syslog(LOG_ERR, "Could not create server socket (%s)", strerror(errno));
        exit(EXIT_FAILURE);
    }

    /* Receive datagrams and return copies to senders */

    for (;;) {
        len = sizeof(struct sockaddr_storage);
        numRead = recvfrom(sfd, buf, BUF_SIZE, 0,
                           (struct sockaddr *) &claddr, &len);
        if (numRead == -1)
            errExit("recvfrom");

        if (sendto(sfd, buf, numRead, 0, (struct sockaddr *) &claddr, len)
                != numRead)
            syslog(LOG_WARNING, "Error echoing response to %s (%s)",
                   inetAddressStr((struct sockaddr *) &claddr, len,
                                  addrStr, IS_ADDR_STR_LEN),
                   strerror(errno));
    }
}
/*
This function is used to ensure that there is a URI server associated with the IPC directory that is being used.  It does this by checking if one exists (in which case it returns its address) and creating a new one if there isn't one already.
@param inputPathForMessagingDirectory: The path to the directory that the IPC files for ZeroMQ will be created in
@return: The IPC address of the server process
@exception: This function will throw exceptions if the directory is invalid, a fork call fails, a memory allocation fails or a file operation fails.  
*/
std::string localURIEngine::ensureDirectoryURIServerSingletonIsRunningAndGetAddress(const std::string &inputPathForMessagingDirectory)
{
   //See if there is a server going already and start one if there is not
   //Check if there is an existing localURIServer
   uint64_t existingSingletonID;
   if(checkForExistingURISingletonsAndCleanUpSingletonIPCFiles   (inputPathForMessagingDirectory, &existingSingletonID))
   {
      //A singleton exists, so return its IPC path
      return std::string(URI_SERVER_SINGLETON_IPC_FORMAT) + std::to_string(existingSingletonID);
   }


   //No singleton exists, so spawn one (might replace this with a simple system call)
   pid_t forkResult = fork();

   if(forkResult == -1)
   {
      throw SOMException(std::string("Error forking to create database singleton\n"), FORK_ERROR, __FILE__, __LINE__);
   }

   if(forkResult == 0) 
   {
//We are in the child process
//Make a singleton
      try
      {

         if(becomeDaemon() != 1)
         {
            _exit(0);
         }

       //Make singleton object
         localURIServerSingleton databaseSingleton(inputPathForMessagingDirectory);

         //Process requests forever
         databaseSingleton.processRequests();
         _exit(0);
      }
      catch(std::exception &inputException)
      {
         //Swallow any exceptions and exit to make sure child process doesn't call destructor the parent's ZMQ resources
//fprintf(stderr, "Attempt to start database singleton failed: %s\n", inputException.what());
         _exit(0); //Return successfully
      }
   }

//Wait for up to a certain amount of time in increments of 100 milliseconds for a database server singleton to start
   uint64_t singletonID;
   bool foundSingleton=false;
   for(int i=0; i<HOW_LONG_TO_WAIT_FOR_DATABASE_SERVER_IN_MILLISECONDS; i+=100)
    {

      if(checkForExistingURISingletonsAndCleanUpSingletonIPCFiles(inputPathForMessagingDirectory, &singletonID))
      {
         foundSingleton = true;
         break;
      }

      if(usleep(100*1000)!=0)
      {
         throw SOMException(std::string("Error occurred attempting to sleep\n"), SYSTEM_ERROR, __FILE__, __LINE__);
      }
   }


   if(!foundSingleton)
   {
      throw SOMException(std::string("Attempt to start singleton failed\n"), SYSTEM_ERROR, __FILE__, __LINE__);
   }


   //A singleton exists, so return it
   return std::string(URI_SERVER_SINGLETON_IPC_FORMAT) + std::to_string(singletonID);
}
Exemple #10
0
int
main(int argc, char **argv)
{
    int oldpid, oldumask, fd, parentPid;
    char *pt, *errorLogFile, **opts;

    /* make sure at least world write access is disabled */
    if (((oldumask = umask(022)) & 002) == 002)
        (void)umask(oldumask);

    /* give /dev/null as stdin */
    if ((fd = open("/dev/null", O_RDONLY)) > 0) {
        dup2(fd, 0);
        close(fd);
    }
    if (fcntl(1, F_GETFD) < 0)
        dup2(0, 1);
    if (fcntl(2, F_GETFD) < 0)
        dup2(0, 2);

#ifndef nowMonotonic
    nowMonotonic = sysconf(_SC_MONOTONIC_CLOCK) >= 200112L;
#endif

#if KDM_LIBEXEC_STRIP == -1
    prog = strrchr(argv[0], '/');
    progname = prog = prog ? prog + 1 : argv[0];
#else
    if (argv[0][0] == '/') {
        if (!strDup(&progpath, argv[0]))
            panic("Out of memory");
    } else
# ifdef __linux__
    {
        /* note that this will resolve symlinks ... */
        int len;
        char fullpath[PATH_MAX];
        if ((len = readlink("/proc/self/exe", fullpath, sizeof(fullpath))) < 0)
            panic("Invoke with full path specification or mount /proc");
        if (!strNDup(&progpath, fullpath, len))
            panic("Out of memory");
    }
# else
#  if 0
        panic("Must be invoked with full path specification");
#  else
    {
        char directory[PATH_MAX+1];
        if (!getcwd(directory, sizeof(directory)))
            panic("Can't find myself (getcwd failed)");
        if (strchr(argv[0], '/')) {
            strApp(&progpath, directory, "/", argv[0], (char *)0);
        } else {
            int len;
            char *path, *pathe, *name, *thenam, nambuf[PATH_MAX+1];

            if (!(path = getenv("PATH")))
                panic("Can't find myself (no PATH)");
            len = strlen(argv[0]);
            name = nambuf + PATH_MAX - len;
            memcpy(name, argv[0], len + 1);
            *--name = '/';
            do {
                if (!(pathe = strchr(path, ':')))
                    pathe = path + strlen(path);
                len = pathe - path;
                if (!len || (len == 1 && *path == '.')) {
                    len = strlen(directory);
                    path = directory;
                }
                thenam = name - len;
                if (thenam >= nambuf) {
                    memcpy(thenam, path, len);
                    if (!access(thenam, X_OK))
                        goto found;
                }
                path = pathe;
            } while (*path++ != '\0');
            panic("Can't find myself (not in PATH)");
          found:
            if (!strDup(&progpath, thenam))
                panic("Out of memory");
        }
    }
#  endif
# endif
    prog = strrchr(progpath, '/') + 1;
# if KDM_LIBEXEC_STRIP
    for (progname = pt = prog, fd = 0; fd < KDM_LIBEXEC_STRIP + 1; fd++) {
        for (;;) {
            pt--;
            if (pt == progpath)
                panic("Executable is obviously located outside BINDIR");
            if (*pt == '/')
                break;
        }
    }
    *pt = 0;
# endif
#endif

#if !defined(HAVE_SETPROCTITLE) && !defined(NOXDMTITLE)
    title = argv[0];
    titleLen = (argv[argc - 1] + strlen(argv[argc - 1])) - title;
#endif

    /*
     * Parse command line options
     */
    parentPid = getppid();
    errorLogFile = 0;
    if (!(opts = Malloc(2 * sizeof(char *))))
        return 1;
    opts[0] = (char *)"";
    opts[1] = 0;
    while (*++argv) {
        if (**argv != '-')
            break;
        pt = *argv + 1;
        if (*pt == '-')
            pt++;
        if (!strcmp(pt, "help") || !strcmp(pt, "h")) {
            printf("Usage: %s [options] [tty]\n"
"  -daemon\t  - Daemonize even when started by init\n"
"  -nodaemon\t  - Do not daemonize even when started from command line\n"
"  -config <file>  - Use alternative master configuration file\n"
"  -xrm <res>\t  - Override frontend-specific resource\n"
"  -error <file>\t  - Use alternative log file\n"
"  -debug <num>\t  - Debug option bitfield:\n"
"\t\t\t0x1 - core log\n"
"\t\t\t0x2 - config reader log\n"
"\t\t\t0x4 - greeter log\n"
"\t\t\t0x8 - IPC log\n"
"\t\t\t0x10 - session sub-daemon post-fork delay\n"
"\t\t\t0x20 - config reader post-start delay\n"
"\t\t\t0x40 - greeter post-start delay\n"
"\t\t\t0x80 - do not use syslog\n"
"\t\t\t0x100 - core Xauth log\n"
"\t\t\t0x200 - debug greeter theming\n"
"\t\t\t0x400 - valgrind config reader and greeter\n"
"\t\t\t0x800 - strace config reader and greeter\n"
                    , prog);
            exit(0);
        } else if (!strcmp(pt, "daemon")) {
            parentPid = 0;
        } else if (!strcmp(pt, "nodaemon")) {
            parentPid = 1;
        } else if (argv[1] && !strcmp(pt, "config")) {
            strDup(opts, *++argv);
        } else if (argv[1] && !strcmp(pt, "xrm")) {
            opts = addStrArr(opts, *++argv, -1);
        } else if (argv[1] && !strcmp(pt, "debug")) {
            sscanf(*++argv, "%i", &debugLevel);
        } else if (argv[1] && (!strcmp(pt, "error") || !strcmp(pt, "logfile"))) {
            errorLogFile = *++argv;
        } else {
            fprintf(stderr, "\"%s\" is an unknown option or is missing a parameter\n", *argv);
            exit(1);
        }
    }

    /*
     * Only allow root to run in non-debug mode to avoid problems
     */
    if (!debugLevel && getuid()) {
        fprintf(stderr, "Only root wants to run %s\n", prog);
        exit(1);
    }

    initErrorLog(errorLogFile);

    if (parentPid != 1)
        becomeDaemon();

    /*
     * Step 1 - load configuration parameters
     */
    if (!initResources(opts) || scanConfigs(False) < 0)
        logPanic("Config reader failed. Aborting ...\n");

    /* SUPPRESS 560 */
    if ((oldpid = storePid())) {
        if (oldpid == -1)
            logError("Cannot create/lock pid file %s\n", pidFile);
        else
            logError("Cannot lock pid file %s, another xdm is running (pid %d)\n",
                     pidFile, oldpid);
        exit(1);
    }

#ifdef NEED_ENTROPY
    addOtherEntropy();
#endif

    /*
     * We used to clean up old authorization files here. As authDir is
     * supposed to be /var/run/xauth or /tmp, we needn't to care for it.
     */

#ifdef XDMCP
    initXdmcp();
#else
    debug("not compiled for XDMCP\n");
#endif
    if (pipe(signalFds))
        logPanic("Unable to create signal notification pipe.\n");
    registerInput(signalFds[0]);
    registerCloseOnFork(signalFds[0]);
    registerCloseOnFork(signalFds[1]);
    (void)Signal(SIGTERM, sigHandler);
    (void)Signal(SIGINT, sigHandler);
    (void)Signal(SIGHUP, sigHandler);
    (void)Signal(SIGCHLD, sigHandler);
    (void)Signal(SIGUSR1, sigHandler);

    /*
     * Step 2 - run a sub-daemon for each entry
     */
    openCtrl(0);
#ifdef XDMCP
    updateListenSockets();
#endif
    mainLoop();
    closeCtrl(0);
    if (sdRec.how) {
        int pid;
        commitBootOption();
        if (Fork(&pid) <= 0) {
            char *cmd = sdRec.how == SHUT_HALT ? cmdHalt : cmdReboot;
            execute(parseArgs((char **)0, cmd), (char **)0);
            logError("Failed to execute shutdown command %\"s\n", cmd);
            exit(1);
        } else {
            sigset_t mask;
            sigemptyset(&mask);
            sigaddset(&mask, SIGCHLD);
            sigaddset(&mask, SIGHUP);
            sigsuspend(&mask);
        }
    }
    debug("nothing left to do, exiting\n");
    return 0;
}