c - fopen() seems not work when I create a daemon process -
here main source code:
int main(int argc, char *argv[]) { [...] if (become_daemon(0) == -1) { exit(exit_failure); } while (main_loop == loop_continue) { [...] if (log_data(date_temp, data_processed) < 0) { [...] } else { [...] } sleep(measure_rate); } [...] } here functions definitions:
int become_daemon(int flags) { int maxfd, fd; switch (fork()) { case -1: return -1; case 0: break; default: exit(exit_success); } if (setsid() == -1) return -1; switch (fork()) { case -1: return -1; case 0: break; default: exit(exit_success); } if (!(flags & bd_no_mask0)) umask(0); if (!(flags & bd_no_chdir)) chdir("/"); if (!(flags & bd_no_close_file)) { maxfd = sysconf(_sc_open_max); if (maxfd == -1) maxfd = bd_max_close; (fd = 0; fd < maxfd; fd++) close(fd); } if (!(flags & bd_no_reopen_std_fds)) { close(stdin_fileno); fd = open("/dev/null", o_rdwr); if (fd != stdin_fileno) return -1; if (dup2(stdin_fileno, stdout_fileno) != stdout_fileno) return -1; if (dup2(stdin_fileno, stderr_fileno) != stderr_fileno) return -1; } return 0; } int log_data(char *date, double array_data[data_num]) { file *file; if ((file = fopen(datalog_file, "a")) == null) return -1; fprintf(file, "%s ; %.2f ; %.2f ; %.2f ; %.2f ; %.2f ; %.2f\n", date, array_data[0], array_data[1], array_data[2], array_data[3], array_data[4], array_data[5]); fclose(file); return 0; } and here problem:
when compile code become_daemon() function active , execute program, file datalog_file (it's define "xxxxxx.txt") it's not created. if compile without become_daemon() function call, program works fine , file created.
i noticed if add line
sudo /my/folder/program in rc.local run @ boot, starts want but, in these case, not create file datalog_file.
i'm newbie daemon process can tell me cause of behavior?
as ctx mentioned in comment, function become_daemon may change current directory /. if datalog_file relative filename, such "xxxxxx.txt" write in question, daemon fail create in system root directory, unless has root privileges.
either not change current directory passing bd_no_chdir argument become_daemon or make datalog_file absolute path.
Comments
Post a Comment