⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 test3.c

📁 这个是学习嵌入式开发的重要例子
💻 C
字号:
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <string.h>#include <errno.h>#include <syslog.h>/////////////////////////////////////////////////////////////////////// macro definitions//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function protypes/////////////////////////////////////////////////////////////////////void daemon_init(char *ident);void usage(char *prog);/////////////////////////////////////////////////////////////////////// Main function/////////////////////////////////////////////////////////////////////int main(int argc, char **argv){  if (argc < 2)  {    usage(argv[0]);    exit(1);  }  if (!strcmp(argv[1], "-d"))  {    fprintf(stdout, "[%d] Starting as a daemon process.\n", getpid());    daemon_init(argv[0]);  }  // void syslog(int priority, const char *message, ... /* arguments */);  syslog(LOG_DEBUG, "Starting %s", argv[0]);#if 0  for (i = 0; i < 10000; i++)  {    fprintf(stdout, ".");    if (i % 80 == 0)    {      fprintf(stdout, "\n");    }  }#endif  sleep(10000);  // void closelog(void);  closelog();  return 0;}void daemon_init(char *ident){  // step 1, fork(), create a new child process, parent process exit.  pid_t pid;  if ((pid = fork()) < 0)  {    fprintf(stderr, "[%d]Create child process failed: %s\n", getpid(), strerror(errno));    exit(1);  }  else if (pid > 0)  {    fprintf(stdout, "[%d]Parent process exited.\n", getpid());    exit(0);  }  // step 2, call setsid() to create a new session, away from controlling terminal  if (setsid() < 0)  {    fprintf(stderr, "[%d]setsid() failed: %s\n", getpid(), strerror(errno));    exit(1);  }  // step 3, chdir(), to root  chdir("/");  // step 4, set umask()  umask(0);  // step 5, close all opened files.  int i;  int open_max = sysconf(_SC_OPEN_MAX);  fprintf(stdout, "[%d] open_max = %d\n", getpid(), open_max);  for (i = 0; i < open_max; i++)  {    close(i);  }  // step 6, open syslog(), and write log message to syslog  // void openlog(const char *ident, int logopt, int facility);  openlog(ident, LOG_PID, LOG_USER);}void usage(char *prog){  fprintf(stdout, "%s <-d>\n", prog);}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -