Search code examples
cprintfexecvquine

Quine create and execute file


I am creating a Quine in C and where i need to create a new c file and then compile it and execute it.

I made a simple snippet to understand why it's not working.

My guess is that execv start the command before fprintf is done writing but i put a sleep and it's wasn't working too.

(All my apologize for this ugliest code but it's not the goal)

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main()
{
    char *cmd[100]= {"sh", "-c", "\"gcc tmp.c && ./a.out\""};

    fprintf(fopen("tmp.c", "w"), "#include <stdio.h>\nint main(){puts(\"Hello World\");}");
    execv("/bin/sh", cmd);
    return (0);
}

Output

sh: gcc tmp.c && ./a.out: No such file or directory

Any idea ?


Solution

  • Your argument array cmd is not terminated with a NULL pointer. Also, it has the quote issue.

    You should also close the file before execv() call. The reason you are not seeing anything in the file is because fprintf() buffering. While all the open files are closed at process exit, you are exec'ing before that.

    int main(void)
    {
    
       char *cmd[]= {"sh", "-c", "gcc tmp.c && ./a.out", (char*)0};
    
        FILE *fp = fopen("tmp.c", "w");
        if (!fp) {
           perror("fopen");
           exit(1);
        }
    
        fprintf(fp, "#include <stdio.h>\nint main(){puts(\"Hello World\");}");
        fclose(fp);
        execv("/bin/sh", cmd);
        perror("execv");
        return (0);
    }