main.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include <stdio.h>
  2. #include <iostream>
  3. #include "../common/comm.h"
  4. #include "api.h"
  5. #include "Protocol.pb.h"
  6. #include "message_queue.h"
  7. #include "../common/iobuffer.h"
  8. #include <cstring>
  9. void daemonize(void) {
  10. signal(SIGTTOU, SIG_IGN);
  11. signal(SIGTTIN, SIG_IGN);
  12. signal(SIGTSTP, SIG_IGN);
  13. if (0 != fork()) exit(0);
  14. if (-1 == setsid()) exit(0);
  15. signal(SIGHUP, SIG_IGN);
  16. if (0 != fork()) exit(0);
  17. //if (0 != chdir("/")) exit(0);
  18. }
  19. bool checkOnly()
  20. {
  21. const char filename[] = "./lockfile";
  22. int fd = open (filename, O_WRONLY | O_CREAT , 0644);
  23. int flock = lockf(fd, F_TLOCK, 0 );
  24. if (fd == -1) {
  25. return false;
  26. }
  27. //给文件加锁
  28. if (flock == -1) {
  29. return false;
  30. }
  31. //程序退出后,文件自动解锁
  32. return true;
  33. }
  34. std::string getpath()
  35. {
  36. char exec_name [BUFSIZ];
  37. readlink ("/proc/self/exe", exec_name, BUFSIZ);
  38. int32_t len=strlen(exec_name);
  39. for(int i=len;i>=0;i--)
  40. {
  41. if(exec_name[i]=='/')
  42. {
  43. exec_name[i]=0;
  44. break;
  45. }
  46. }
  47. return std::string(exec_name);
  48. }
  49. int main(int argc,char *argv[])
  50. {
  51. // daemonize();
  52. auto path=getpath();
  53. std::cout<<path<<std::endl;
  54. if(-1==chdir(path.c_str())) return 0;
  55. if(checkOnly()==false)
  56. {
  57. std::cout<<"进程已经在运行"<<std::endl;
  58. return 0;
  59. }
  60. //
  61. std::cout<<"进程启动..."<<std::endl;
  62. char temp[BUFSIZ];
  63. getcwd(temp,BUFSIZ);
  64. std::cout<<temp<<std::endl;
  65. CMessageQueue Q;
  66. Q.Create();
  67. while(true)
  68. {
  69. Q.Process();
  70. }
  71. //gtk_main();
  72. return 0;
  73. }