How to write a a self replacing/updating binary?
c, c++, linux
Solution
Rename the currently running binary to something else, write the new binary, run it, then delete the renamed binary later.
Problem
I am trying to write a C program which may lookup a url and incase a new version of it is avaiable it should be able to update itself. The method i have tried: Forkout a new process to Download the new binary say BINARY.tmp, code i am using to forkout the is: ``` 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 tries to overwrite the original BINARY for example you may consider the routine which forks out may be doing: ``` forkout_cmd("wget -O BINARY.tmp https://someurl.com/BINARY_LATEST; /bin/mv -f BINARY.tmp BINARY"); ``` But, the overwriting fails since the original binary is still in execution and hence busy on disk, can somebody provide me some suggestions here to overcome this problem. Thanks in advance.