linux下c/c++程序重启自己

在程序自动升级的时候需要自己重新启动自己
示例代码:

点击(此处)折叠或打开

  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. int main(int argc, char **argv)
  6. {
  7.     char buf[32] = {};
  8.     char *exec_argv[] = { argv[0], buf, 0 };
  9.     int count = argc > 1 ? atoi(argv[1]) : 0;
  10.  
  11.     printf("Running: %s %d\n", argv[0], count);
  12.     snprintf(buf, sizeof(buf), "%d", count+1);
  13.     sleep(5);
  14.  
  15.     execv("/proc/self/exe", exec_argv);
  16.  
  17.     /* NOT REACHED */
  18.     return 0;
  19. }

zengming@linux-eshv:~/test> g++ main.cpp
zengming@linux-eshv:~/test> ./a.out 1
Running: ./a.out 1
Running: ./a.out 2
Running: ./a.out 3
^C
程序员群:31843264

你可能感兴趣的:(C/C++)