How to write a self-replaceable / update binary?

I am trying to write a C program that can search for a URL and display a new version available for updating it.

The method I tried:

  • Run a new process to load the new binary. Say BINARY.tmp, the code I use for forkout:

    int
    forkout_cmd(char *cmdstr) {
      pid_t pid;
      char *cmd[4];
    
      cmd[0] = "/bin/bash";
      cmd[1] = "-c";
      cmd[2] = cmdstr;
      cmd[3] = NULL;
    
      pid = vfork();
      if( pid == -1 ) {
        logmsg("Forking for upgradation failed.");
        return -1;
      }else if( pid == 0 ){
        /* we are in child process */
        execvp(cmd[0], cmd);
        logmsg("execl failed while executing upgradation job.");
      }else{
        /* need not to wait for the child to complete. */
        wait(NULL);
      }
        return 0;
    }
    
  • The new process is trying to overwrite the original BINARY

    for example, you can consider a routine that can be implemented:

    forkout_cmd("wget -O BINARY.tmp https://someurl.com/BINARY_LATEST; /bin/mv -f BINARY.tmp BINARY");
    

But the rewriting fails because the source binary is still in progress and therefore busy on disk, can anyone give me some suggestions to solve this problem.

Thanks in advance.

+4
source share
2

, , , .

+7

binary.tmp , , / (, , , 100% ), .

Linux , - ( , , , , ).

. . "" , , . - , .

( ) .

+5

Source: https://habr.com/ru/post/1529265/


All Articles