简体   繁体   中英

linux overwrite running binary

How would i do this in linux using C ? I need to write update function that downloads update using wget, then replaces old file with an update, and then starts update file. One idea was using bash script but that didn't work out. Any suggestions?

EDIT:here is code similiar to what i tried

char *p_name = "example"; /* name of the running executable */

void update(char *update_url)
{
        if(!fork())
                /* download file to temporary location */
                execlp("wget", "wget" "-q", update_url, "-O", "tmp", NULL);
        wait(NULL);
        FILE *fp = fopen("tmp.sh", "w");
        /* write bash script */
        fprintf(fp, "sleep 5\nmv tmp %s\nchmod +x %s\nrm tmp.sh",
                p_name, p_name);
        fclose(fp);
        execlp("bash", "bash", "tmp.sh", NULL);
}

Overwriting a running program doesn't actually overwrite the file, it basically creates a new file, while marking the old file to be removed when the program exits.

After your script have downloaded the new program, you have to kill the running program, and then restart it. It will start with the new program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM