I have an strange issue. I am not very good in C language. I am trying to create a daemon to execute my bash script based service in Linux. To make it easy I have made the code simple. Below is my code.
int main(int argc, char* argv)
pid_t process_id = 0;
pid_t sid = 0;
process_id = fork();
if (process_id < 0)
if (process_id > 0)
printf("daemon creatd with process id %d \n", process_id);
sid = setsid();
if(sid < 0)
fprintf(stderr, "Return error\n");
int status = system("ls");
openlog("slog", LOG_PID|LOG_CONS, LOG_USER);
syslog(LOG_INFO, "Returned status is %d", status);
In case it is not clear from other comments and answers,
ls writes its output to stdout. If it can not write to stdout it terminates and (apparently) sets an status code of 512 (non-zero in any case).
The child process will inherit stdout from the parent, so if you do not close stdout in the parent, the child will have a stdout to write to and the command will succeed. If you close stdout, then the child has nowhere to write its output and the error occurs.
ls is just an example for this question, your actual child process is writing to stdout which results in the same problem.
The simplest way around this, and assuming that you do not want the child's output, is to redirect the child's stdout on the command line:
int status = system("ls >/dev/null 2>&1");
This will redirect stdout and stderr to
/dev/null, effectively throwing away the child's output while still giving it somewhere to write to.