refactoring
authorAlexey Chernobaev <achernobaev@dev.rtsoft.ru>
Wed, 29 Aug 2018 19:01:53 +0000 (22:01 +0300)
committerAleksei Vereshchagin <avereschagin@dev.rtsoft.ru>
Mon, 3 Sep 2018 15:21:42 +0000 (18:21 +0300)
profctl.c

index c05e434..0abf2fa 100644 (file)
--- a/profctl.c
+++ b/profctl.c
@@ -48,10 +48,7 @@ static char *oname = NULL;
 
 static int isPipeOwner = 0;
 
-static FILE *orig_stdin = NULL;
-static FILE *orig_stdout = NULL;
-static FILE *orig_stderr = NULL;
-
+static FILE *log = NULL;
 static int controlPort = -1;
 static int dataPort = -1;
 static int statPort = -1;
@@ -63,6 +60,8 @@ static FILE *ctrl_file_out = NULL;
 static FILE *data_file_out = NULL;
 static FILE *stat_file_out = NULL;
 
+static volatile int exiting = 0;
+
 static struct option long_options[] = {
        {"appid",       required_argument, 0, 'a'},
        {"pipe",        required_argument, 0, 'p'},
@@ -79,11 +78,10 @@ static struct option long_options[] = {
        {0, 0, 0, 0}
 };
 
-static void log_time_zone_info()
+static void log_time_zone_info(time_t start_time)
 {
-       time_t t = time(NULL);
-       struct tm tm = *localtime(&t);
-       fprintf(stderr, "Local time: %04d-%02d-%02d %02d:%02d:%02d. Time zone: %s (UTC",
+       struct tm tm = *localtime(&start_time);
+       fprintf(log, "Local time: %04d-%02d-%02d %02d:%02d:%02d. Time zone: %s (UTC",
                tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_zone);
        char sign;
        if (tm.tm_gmtoff >= 0) {
@@ -94,8 +92,8 @@ static void log_time_zone_info()
                tm.tm_gmtoff = -tm.tm_gmtoff;
        }
        int minutes = tm.tm_gmtoff / 60;
-       fprintf(stderr, "%c%02d%02d). ", sign, minutes / 60, minutes % 60);
-       fprintf(stderr, "Using UTC time in the log\n");
+       fprintf(log, "%c%02d%02d). ", sign, minutes / 60, minutes % 60);
+       fprintf(log, "Using UTC time in the log\n");
 }
 
 // et: epoch time; tm: UTC time (broken-down representation); millisec: milliseconds
@@ -131,123 +129,151 @@ static void log_current_time()
        struct tm tm;
        int millisec;
        get_current_time(NULL, &tm, &millisec);
-       fprintf(stderr, "%02d-%02d-%02d %02d:%02d:%02d.%03d ",
+       fprintf(log, "%02d-%02d-%02d %02d:%02d:%02d.%03d ",
                tm.tm_year + 1900 - 2000, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, millisec);
 }
 
-static pthread_mutex_t stderr_lock;
+static pthread_mutex_t log_lock;
 
-static void log_error(const char *fmt, ...)
+static void flog(const char *fmt, ...)
 {
-       pthread_mutex_lock(&stderr_lock);
+       pthread_mutex_lock(&log_lock);
        log_current_time();
        va_list arg;
        va_start(arg, fmt);
-       vfprintf(stderr, fmt, arg);
-       fprintf(stderr, "\n");
+       vfprintf(log, fmt, arg);
        va_end(arg);
-       fflush(stderr);
-       pthread_mutex_unlock(&stderr_lock);
+       fprintf(log, "\n");
+       fflush(log);
+       pthread_mutex_unlock(&log_lock);
 }
 
-static void log_prefixed_system_error(const char *prefix, const char *msg)
+// write an error message to log: first write 'prefix' (if not null), then the current time,
+// then the formatted message, then the system error message (corresponding to 'error_code',
+// and a new line
+static void log_prefixed_system_error(FILE *file, int error_code, const char *prefix, const char *fmt, va_list arg)
 {
-       int t = errno;
-       pthread_mutex_lock(&stderr_lock);
+       pthread_mutex_lock(&log_lock);
+       if (file == NULL) {
+               file = log;
+       }
        if (prefix != NULL) {
-               fputs(prefix, stderr);
+               fputs(prefix, file);
        }
        log_current_time();
-       errno = t;
-       perror(msg);
-       fflush(stderr);
-       pthread_mutex_unlock(&stderr_lock);
+       vfprintf(file, fmt, arg);
+       fprintf(file, ": %s\n", strerror(error_code));
+       fflush(file);
+       pthread_mutex_unlock(&log_lock);
 }
 
-static void log_system_error(const char *msg)
+static void log_system_error(const char *fmt, ...)
 {
-       log_prefixed_system_error(NULL, msg);
+       va_list arg;
+       va_start(arg, fmt);
+       log_prefixed_system_error(log, errno, NULL, fmt, arg);
+       va_end(arg);
 }
 
-static void log_system_error_and_exit(const char *msg)
+static void log_system_error_and_exit(const char *fmt, ...)
 {
-       log_prefixed_system_error("[FATAL] ", msg);
-       if ((orig_stderr != NULL) && (orig_stderr != stderr)) { // repeat to actual stderr
-               stderr = orig_stderr;
-               log_prefixed_system_error("[FATAL] ", msg);
+       int error_code = errno;
+       va_list arg;
+       va_start(arg, fmt);
+       log_prefixed_system_error(log, error_code, "[FATAL] ", fmt, arg);
+       // repeat to actual stderr
+       if (log != stderr) {
+               log_prefixed_system_error(stderr, error_code, "[FATAL] ", fmt, arg);
        }
+       va_end(arg);
        exit(1);
 }
 
+static void log_system_error_and_thread_exit(const char *fmt, ...)
+{
+       int error_code = errno;
+       va_list arg;
+       va_start(arg, fmt);
+       log_prefixed_system_error(log, error_code, "[THREAD EXIT] ", fmt, arg);
+       // repeat to actual stderr
+       if (log != stderr) {
+               log_prefixed_system_error(stderr, error_code, "[THREAD EXIT] ", fmt, arg);
+       }
+       va_end(arg);
+       pthread_exit(NULL);
+}
+
+static int openFileProcess();
 static int openPort(int port);
-static void openFileProcess();
 static FILE *pipef;
 
 static void *output_thread(void *arg)
 {
-       openFileProcess();
-
-       if (dataPort > 0) {
-               data_socket = openPort(dataPort);
-               data_file_out = fdopen(data_socket, "w");
-               if (data_file_out == NULL) {
-                       log_system_error_and_exit("fdopen(data,w)");
+       if (openFileProcess() == 0) {
+               if (dataPort > 0) {
+                       data_socket = openPort(dataPort);
+                       if (data_socket < 0) {
+                               exit(1); // TODO!!
+                       }
+                       data_file_out = fdopen(data_socket, "w");
+                       if (data_file_out == NULL) {
+                               log_system_error_and_thread_exit("fdopen(data,w)");
+                       }
+                       fprintf(data_file_out, "ready\n");
+                       fflush(data_file_out);
+               }
+               else {
+                       data_file_out = stdout;
                }
-               fprintf(data_file_out, "ready\n");
-               fflush(data_file_out);
-       }
 
-       int linesRead = 0;
-       char *buffer = NULL;
-       size_t lsize = 0;
+               int linesRead = 0;
 
-       while (getline(&buffer, &lsize, pipef) != -1) {
-               ++linesRead;
-               if (fputs(buffer, data_file_out) < 0) {
-                       log_error("fputs failed - exiting");
-                       break;
+               char *buffer = NULL;
+               size_t lsize = 0;
+               while (getline(&buffer, &lsize, pipef) != -1) {
+                       ++linesRead;
+                       if (fputs(buffer, data_file_out) < 0) {
+                               flog("fputs failed - exiting");
+                               break;
+                       }
                }
-       }
+               free(buffer);
 
-       free(buffer);
-       if (verbose) {
-               log_error("output thread exits (%d lines read)", linesRead);
+               if (verbose) {
+                       flog("output thread exits (%d lines read)", linesRead);
+               }
        }
-
-       exit(0);
+       exit(0); // TODO!!
 }
 
 #if TIZEN
 static void *wait_thread(void *arg)
 {
-       while (aul_app_get_status_bypid(pid) >= 0)
+       while (aul_app_get_status_bypid(pid) >= 0) {
                sleep(1);
+       }
        if (verbose) {
-               log_error("application finished");
+               flog("application finished");
        }
-       exit(0);
+       exiting = 1; // TODO!! exit?
 }
 #endif /* TIZEN */
 
 // On Tizen, launch_app won't terminate until stdin, stdout and stderr are closed
-static void finish_close_stdio()
+// TODO!! is needed?
+static void close_stdio()
 {
-       if (orig_stdin != NULL) {
-               fclose(orig_stdin);
-       }
-       if (orig_stdout != NULL) {
-               fclose(orig_stdout);
-       }
-       if (orig_stderr != NULL) {
-               fclose(orig_stderr);
-       }
+       fclose(stdin);
+       fclose(stdout);
+       fclose(stderr);
 }
 
 static void finish()
 {
+       flog("exit handler called");
 #if TIZEN
        if (controlPort < 0) {
-               tcsetattr(0,TCSANOW, &sterm);
+               tcsetattr(0, TCSANOW, &sterm);
        }
 #endif /* TIZEN */
        if (pipef != NULL) {
@@ -256,21 +282,17 @@ static void finish()
                        unlink(pname);
                }
        }
-       if (ctrl_file_in != NULL) {
-               if (ctrl_file_in != orig_stdin) {
-                       fclose(ctrl_file_in);
-               }
+       if (ctrl_file_in != NULL && ctrl_file_in != stdin) {
+               fclose(ctrl_file_in);
        }
-       if (ctrl_file_out != NULL) {
-               if (ctrl_file_out != orig_stdout) {
-                       fclose(ctrl_file_out);
-               }
+       if (ctrl_file_out != NULL && ctrl_file_out != stdout) {
+               fclose(ctrl_file_out);
        }
-       if (data_file_out != NULL) {
-               fflush(data_file_out);
-               if (data_file_out != orig_stdout) {
-                       fclose(data_file_out);
-               }
+       if (data_file_out != NULL && data_file_out != stdout) {
+               fclose(data_file_out);
+       }
+       if (stat_file_out != NULL && stat_file_out != stdout) {
+               fclose(stat_file_out);
        }
        if (control_socket >= 0) {
                close(control_socket);
@@ -281,11 +303,10 @@ static void finish()
        if (stat_socket >= 0) {
                close(stat_socket);
        }
-       log_error("=== finished ===");
-       if (stderr != orig_stderr) {
-               fclose(stderr);
+       flog("=== finished ===");
+       if (log != stderr) {
+               fclose(log);
        }
-       finish_close_stdio();
        kill(getpid(), SIGKILL);
 }
 
@@ -313,40 +334,44 @@ static void split(char *line, char **array, int n)
        }
 }
 
-static void *outstat(void *arg)
+static void *outstat_thread(void *arg)
 {
        FILE *sstat = fopen("/proc/stat","r");
        if (sstat == NULL ) {
-               log_system_error_and_exit("open /proc/stat");
+               log_system_error_and_thread_exit("open /proc/stat");
        }
 
        FILE *cpuf = fopen("/sys/devices/system/cpu/present","r");
        if (cpuf == NULL ) {
-               log_system_error_and_exit("open /sys/devices/system/cpu/present");
+               log_system_error_and_thread_exit("open /sys/devices/system/cpu/present");
        }
        int tmp, ncpu;
        if (fscanf(cpuf, "%d-%d\n", &tmp, &ncpu) < 2) {
-               log_system_error_and_exit("fscanf(cpuf) failed");
+               log_system_error_and_thread_exit("fscanf(cpuf) failed");
        }
        fclose(cpuf);
        ncpu = ncpu - tmp + 1;
 
+       if (stat_file_out == NULL) {
+               stat_file_out = stdout;
+       }
+
        long psize = sysconf(_SC_PAGESIZE);
        fprintf(stat_file_out, "psize %ld ncpu %d\n", psize, ncpu);
 
        FILE *memf = fopen("/proc/meminfo", "r");
        if (memf == NULL ) {
-               log_system_error_and_exit("open /proc/meminfo");
+               log_system_error_and_thread_exit("open /proc/meminfo");
        }
 
        char *statmname;
        if (asprintf(&statmname, "/proc/%d/statm", pid) == -1) {
-               log_system_error_and_exit("asprintf");
+               log_system_error_and_thread_exit("asprintf");
        }
 
        char *statname;
        if (asprintf(&statname, "/proc/%d/stat", pid) == -1) {
-               log_system_error_and_exit("asprintf");
+               log_system_error_and_thread_exit("asprintf");
        }
 
        // Sometimes we can't successfully open /proc/$pid files due to strange
@@ -360,7 +385,7 @@ static void *outstat(void *arg)
        {
                pmstat = fopen(statmname, "r");
                if (pmstat == NULL) {
-                       log_system_error("open /proc/$pid/statm");
+                       log_system_error("open %s", statmname);
                        usleep(100000);
                        continue;
                }
@@ -369,7 +394,8 @@ static void *outstat(void *arg)
 
        if (pmstat == NULL)
        {
-               exit(1);
+               flog("cannot open %s - exiting", statmname);
+               pthread_exit(NULL);
        }
 
        FILE *pstat;
@@ -377,25 +403,32 @@ static void *outstat(void *arg)
        {
                pstat = fopen(statname, "r");
                if (pstat == NULL) {
-                       log_system_error("open /proc/$pid/stat");
+                       log_system_error("open %s", statname);
                        usleep(100000);
                        continue;
                }
                break;
        }
 
-       if (pstat == NULL)
-       {
-               exit(1);
+       if (pstat == NULL) {
+               flog("cannot open %s - exiting", statname);
+               pthread_exit(NULL);
        }
 
        free(statmname);
        free(statname);
 
        if (verbose) {
-               log_error("stat output started");
+               flog("stat output started");
        }
 
+       // TODO!! free buffers correctly
+       const int line_buf_size = 256;
+       ssize_t slen, plen, mtlen, mflen;
+       char *sline = malloc(slen = line_buf_size);
+       char *pline = malloc(plen = line_buf_size);
+       char *mtline = malloc(mtlen = line_buf_size);
+       char *mfline = malloc(mflen = line_buf_size);
        while(1) {
                char *stats[5];
                char *pstats[18];
@@ -412,20 +445,16 @@ static void *outstat(void *arg)
 
                fseek(sstat, 0, SEEK_SET);
                fflush(sstat);
-               char *sline = NULL;
-               ssize_t slen = getline(&sline, &slen, sstat);
-               if (slen == -1) {
-                       log_system_error_and_exit("cannot read sstat");
+               if (getline(&sline, &slen, sstat) == -1) {
+                       log_system_error_and_thread_exit("cannot read sstat");
                }
 
-               split(sline, stats, 5);
+               split(sline, stats, sizeof(stats) / sizeof(stats[0]));
 
                fseek(pstat, 0, SEEK_SET);
                fflush(pstat);
-               char *pline = NULL;
-               ssize_t plen = getline(&pline, &plen, pstat);
-               if (plen == -1) {
-                       log_system_error_and_exit("cannot read pstat");
+               if (getline(&pline, &plen, pstat) == -1) {
+                       log_system_error_and_thread_exit("cannot read pstat");
                }
 
                split(pline, pstats, sizeof(pstats) / sizeof(pstats[0]));
@@ -433,20 +462,16 @@ static void *outstat(void *arg)
                fseek(pmstat, 0, SEEK_SET);
                fflush(pmstat);
                if (fscanf(pmstat, "%ld", &pages) < 1) {
-                       log_system_error_and_exit("fscanf(pmstat) failed");
+                       log_system_error_and_thread_exit("fscanf(pmstat) failed");
                }
 
                fseek(memf, 0, SEEK_SET);
                fflush(memf);
-               char *mtline = NULL;
-               ssize_t mtlen = getline(&mtline, &mtlen, memf);
-               if (mtlen == -1) {
-                       log_system_error_and_exit("cannot read memf");
+               if (getline(&mtline, &mtlen, memf) == -1) {
+                       log_system_error_and_thread_exit("cannot read memf");
                }
-               char *mfline = NULL;
-               ssize_t mflen = getline(&mfline, &mflen, memf);
-               if (mflen == -1) {
-                       log_system_error_and_exit("cannot read memf");
+               if (getline(&mfline, &mflen, memf) == -1) {
+                       log_system_error_and_thread_exit("cannot read memf");
                }
 
                split(mtline, mt, 3);
@@ -454,7 +479,7 @@ static void *outstat(void *arg)
 
                struct statvfs fstat;
                if (statvfs(".", &fstat) < 0) {
-                       log_system_error_and_exit("statfs");
+                       log_system_error_and_thread_exit("statvfs");
                }
 
                available = (fstat.f_bsize >= 1024)
@@ -467,7 +492,9 @@ static void *outstat(void *arg)
                        stats[1], stats[3], stats[4], /* user system idle */
                        pstats[14 - 1], pstats[15 - 1], /* puser psystem */
                        mt[1], mf[1], available, pages * psize);
-               fflush(stat_file_out);
+               if (fflush(stat_file_out) != 0) {
+                       log_system_error_and_thread_exit("fflush");
+               }
 
                usleep(timeoutMicrosec);
        }
@@ -477,7 +504,7 @@ static void *outstat(void *arg)
 static void CheckValue(char **value, const char *info)
 {
        if (value[0] != NULL) {
-               log_error("%s is already defined to %s", info, *value);
+               flog("%s is already defined to %s", info, *value);
                exit(1);
        }
        value[0] = optarg;
@@ -488,25 +515,24 @@ static int output_app_info(const aul_app_info *info, void *data)
 {
        if (info == NULL || info->appid == NULL)
                return -1;
-       log_error("pid %d status %d appid %s",
+       fprintf(stderr, "pid %d status %d appid %s\n",
                info->pid, info->status, info->appid);
        return 0;
 }
 #endif /* TIZEN */
 
-static int ListApps(int n)
+static void ListApps(int n)
 {
 #if TIZEN
        aul_app_get_all_running_app_info(output_app_info, NULL);
 #endif /* TIZEN */
-       exit(0);
 }
 
 static int process_option(int argc, char **argv)
 {
        int option_index;
 
-       switch(getopt_long(argc, argv, "-a:p:vle:o:it:wc:d:s:",
+       switch (getopt_long(argc, argv, "-a:p:vle:o:it:wc:d:s:",
                long_options, &option_index)) {
        case 1:
                if (appid == NULL) {
@@ -514,7 +540,7 @@ static int process_option(int argc, char **argv)
                } else if (pname == NULL) {
                        pname = optarg;
                } else {
-                       log_error("Extra argument %s", optarg);
+                       flog("Extra argument %s", optarg);
                        exit(1);
                }
                break;
@@ -562,28 +588,29 @@ static int find_pid(const aul_app_info *info, void *data)
 
 static void waitappid(int n)
 {
-       if (appid == NULL)
+       if (appid == NULL) {
                exit(1);
-
+       }
        for (; n > 0; n--) {
                if (aul_app_is_running(appid)) {
                        int npid = 0;
                        aul_app_get_all_running_app_info(find_pid, &npid);
                        if (npid) {
-                               SimpleThread(&wait_thread);
                                pid = npid;
+                               SimpleThread(&wait_thread);
                                return;
                        }
                }
                sleep(1);
        }
+       flog("cannot find application %s", appid);
        exit(1);
 }
 
 static int app_launch_handler(int npid, const char *app_id, void *data)
 {
        if (verbose) {
-               log_error("app_launch_handler %d - %s", npid, app_id);
+               flog("app_launch_handler %d - %s", npid, app_id);
        }
 
        if (pid > 0 || strcmp(app_id, appid))
@@ -596,7 +623,7 @@ static int app_launch_handler(int npid, const char *app_id, void *data)
 static int app_dead_handler(int npid, void *data)
 {
        if (verbose) {
-               log_error("app_dead_handler %d", npid);
+               flog("app_dead_handler %d", npid);
        }
 
        if (npid != pid)
@@ -608,94 +635,106 @@ static int app_dead_handler(int npid, void *data)
 }
 #endif /* TIZEN */
 
-static void openFileProcess()
+static int openFileProcess()
 {
        if (ename == NULL) {
                pipef = fopen(pname, "r");
                if (pipef == NULL) {
-                       log_system_error_and_exit("fopen");
+                       log_system_error("fopen(%s)", pname);
+                       return -1;
                }
-               return;
+               return 0;
        }
 
        if (access(ename, X_OK)) {
-               log_system_error_and_exit("access");
+               log_system_error("access(%s)", ename);
+               return -1;
        }
 
        /* We must start interpreter process */
        int pipefd[2];
        if (pipe(pipefd)) {
-               log_system_error_and_exit("pipe");
+               log_system_error("pipe");
+               return -1;
        }
 
        if (verbose) {
-               log_error("pipefd: [%d, %d]", pipefd[0], pipefd[1]);
+               flog("pipefd: [%d, %d]", pipefd[0], pipefd[1]);
        }
 
        int id = open(pname, O_RDONLY);
        if (id < 0) {
-               log_system_error_and_exit("open");
+               log_system_error("open(%s)", pname);
+               return -1;
        }
 
        if (verbose) {
-               log_error("pname id: %d", id);
+               flog("pname id: %d", id);
        }
 
        int pid = fork();
        if (pid == -1) {
-               log_system_error_and_exit("fork");
+               log_system_error("fork");
+               return -1;
        }
 
        if (pid == 0) { /* Child */
                close(pipefd[0]);
                if (verbose) {
-                       log_error("CHILD close(%d)", pipefd[0]);
+                       flog("CHILD close(%d)", pipefd[0]);
                }
                dup2(pipefd[1], 1);     /* stdout */
                if (verbose) {
-                       log_error("CHILD dup2(%d, 1)", pipefd[1]);
+                       flog("CHILD dup2(%d, 1)", pipefd[1]);
                }
                dup2(id, 0);            /* stdin */
                if (verbose) {
-                       log_error("CHILD dup2(%d, 0)", id);
+                       flog("CHILD dup2(%d, 0)", id);
                }
                if (verbose) {
-                       log_error("CHILD execl(%s)", ename);
+                       flog("CHILD execl(%s)", ename);
                }
                execl(ename, ename, NULL);
-               log_system_error_and_exit("execl"); // execl returns only in case of error
+               log_system_error("CHILD execl(%s)", ename); // execl returns only in case of error
+               return -1;
        }
 
        /* Parent */
        close(pipefd[1]);
        if (verbose) {
-               log_error("PARENT close(%d)", pipefd[1]);
+               flog("PARENT close(%d)", pipefd[1]);
        }
 
        close(id);
        if (verbose) {
-               log_error("PARENT close(%d)", id);
+               flog("PARENT close(%d)", id);
        }
 
        pipef = fdopen(pipefd[0], "r");
        if (pipef == NULL) {
-               log_system_error_and_exit("fopen");
+               log_system_error("PARENT fdopen(%d, \"r\")", pipefd[0]);
+               return -1;
        }
        if (verbose) {
-               log_error("PARENT fdopen(%d, \"r\")", pipefd[0]);
+               flog("PARENT fdopen(%d, \"r\")", pipefd[0]);
        }
+
+       return 0;
 }
 
 static int openPort(int port)
 {
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if (sock < 0) {
-               log_system_error_and_exit("socket");
+               log_system_error("socket");
+               return sock;
        }
 
        int enable = 1;
        if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) {
-               log_system_error_and_exit("setsockopt");
+               log_system_error("setsockopt");
+               close(sock);
+               return -1;
        }
 
        struct sockaddr_in saddr = {0};
@@ -704,24 +743,30 @@ static int openPort(int port)
        saddr.sin_port = htons(port);
 
        if (bind(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
-               log_system_error_and_exit("bind");
+               log_system_error("bind");
+               close(sock);
+               return -1;
        }
 
        if (listen(sock, 5) < 0) {
-               log_system_error_and_exit("listen");
+               log_system_error("listen");
+               close(sock);
+               return -1;
        }
 
        if (verbose) {
-               log_error("waiting for connection to port %d", port);
+               flog("waiting for connection to port %d", port);
        }
        struct sockaddr_in caddr;
        int csize = sizeof(caddr);
        int result = accept(sock, (struct sockaddr *)&caddr, &csize);
        if (result < 0) {
-               log_system_error_and_exit("accept");
+               log_system_error("accept");
+               close(sock);
+               return -1;
        }
        if (verbose) {
-               log_error("accepted connection to port %d", port);
+               flog("accepted connection to port %d", port);
        }
        close(sock);
        return result;
@@ -729,14 +774,13 @@ static int openPort(int port)
 
 int main(int argc, char **argv)
 {
-       orig_stdin = stdin;
-       orig_stdout = stdout;
-       orig_stderr = stderr;
+       time_t start_time = time(NULL);
 
-       atexit(finish_close_stdio);
+       log = stderr;
 
-       if (pthread_mutex_init(&stderr_lock, NULL) != 0)
-       {
+       atexit(close_stdio);
+
+       if (pthread_mutex_init(&log_lock, NULL) != 0) {
                perror("mutex init failed\n");
                return 1;
        }
@@ -744,12 +788,6 @@ int main(int argc, char **argv)
 #if TIZEN
        struct termios term;
 #endif /* TIZEN */
-       char *line = NULL;
-       ssize_t len = 0;
-
-       ctrl_file_in = stdin;
-       data_file_out = stdout;
-       stat_file_out = stdout;
 
        while(!process_option(argc, argv));
 
@@ -757,7 +795,7 @@ int main(int argc, char **argv)
 
 #if TIZEN
        if (appid == NULL) {
-               log_error("Unknown app id");
+               flog("Unknown app id");
                exit(1);
        }
 #endif /* TIZEN */
@@ -766,16 +804,15 @@ int main(int argc, char **argv)
                oname = "/tmp/profctl.log";
        }
 
-       FILE* redir_stderr = fopen(oname, "w");
-       if (redir_stderr == NULL) {
+       log = fopen(oname, "w");
+       if (log == NULL) {
                log_system_error_and_exit("freopen");
        }
-       setlinebuf(redir_stderr);
-       stderr = redir_stderr;
+       setlinebuf(log);
 
        if (verbose) {
-               log_error("=== started ===");
-               log_time_zone_info();
+               fprintf(stderr, "=== Started (pid: %d) ===\n", getpid());
+               log_time_zone_info(start_time);
                int i;
                for (i = 0; i < argc; i++) {
                        fprintf(stderr, "argv[%d] = %s\n", i, argv[i]);
@@ -785,7 +822,7 @@ int main(int argc, char **argv)
        if (pname && isPipeOwner) {
                unlink(pname);
                if (mkfifo(pname, 0666)) {
-                       log_system_error_and_exit("mkfifo");
+                       log_system_error_and_exit("mkfifo(%s)", pname);
                }
 #if TIZEN
                /* This may be useful for "root on" start */
@@ -805,12 +842,15 @@ int main(int argc, char **argv)
                term.c_lflag &= ~(ECHO|ECHONL); /* no echo and so on */
                term.c_oflag &= ~OPOST; /* no additional CR and so on */
 
-               tcsetattr(0,TCSANOW, &term);
+               tcsetattr(0, TCSANOW, &term);
        }
 #endif /* TIZEN */
 
        if (controlPort > 0) {
                control_socket = openPort(controlPort);
+               if (control_socket < 0) {
+                       exit(1);
+               }
                ctrl_file_in = fdopen(control_socket, "r");
                if (ctrl_file_in == NULL) {
                        log_system_error_and_exit("fdopen(control,r)");
@@ -822,9 +862,15 @@ int main(int argc, char **argv)
                fprintf(ctrl_file_out, "ready\n");
                fflush(ctrl_file_out);
        }
+       else {
+               ctrl_file_in = stdin;
+       }
 
        if (doinfo && (statPort > 0)) {
                stat_socket = openPort(statPort);
+               if (stat_socket < 0) {
+                       exit(1);
+               }
                stat_file_out = fdopen(stat_socket, "w");
                if (stat_file_out == NULL) {
                        log_system_error_and_exit("fdopen(stat,w)");
@@ -841,25 +887,30 @@ int main(int argc, char **argv)
 #endif /* TIZEN */
 
        /* Read command loop */
-       while((len = getline(&line, &len, ctrl_file_in)) != -1) {
+       ssize_t len;
+       char *line = malloc(len = 16);
+       while (!exiting && (len = getline(&line, &len, ctrl_file_in)) != -1) {
                if (verbose) {
                        if ((len > 0) && (line[len - 1] == '\n')) {
                                line[len - 1] = 0;
                        }
-                       log_error("line: %s", line);
+                       flog("line: %s", line);
                }
                if ((pid != -1) && !strncmp(line, "exit", 4)) {
                        kill(pid, SIGHUP);
                        break;
                } else if ((pid != -1) && !strncmp(line, "kill", 4)) {
-                       if (kill(pid, SIGINT))
+                       if (kill(pid, SIGINT)) {
                                log_system_error("kill");
+                       }
                } else if ((pid != -1) && !strncmp(line, "start", 5)) {
-                       if (kill(pid, SIGRTMIN+8))
+                       if (kill(pid, SIGRTMIN + 8)) {
                                log_system_error("kill");
+                       }
                } else if ((pid != -1) && !strncmp(line, "stop", 4)) {
-                       if (kill(pid, SIGRTMIN+7))
+                       if (kill(pid, SIGRTMIN + 7)) {
                                log_system_error("kill");
+                       }
                } else if (!strncmp(line, "test", 4) && (pid == -1)) {
 #if TIZEN
                        waitappid(10); /* try 10 seconds */
@@ -867,10 +918,10 @@ int main(int argc, char **argv)
                        pid = getpid();
 #endif /* TIZEN */
                        if (verbose) {
-                               log_error("pid = %d", pid);
+                               flog("pid = %d", pid);
                        }
                        if (doinfo) {
-                               SimpleThread(&outstat);
+                               SimpleThread(&outstat_thread); // TODO!! clean termination! (check 'exiting')
                        }
                }
                if (ctrl_file_out != NULL) { // echo input line
@@ -878,6 +929,7 @@ int main(int argc, char **argv)
                        fflush(ctrl_file_out);
                }
        } // while
+       free(line);
 
        return 0;
 }