compilation in temporary directory/file with gcc in C program

618 views Asked by At

I recently discovered the mkstemp() function (see this link) but it does not fully meet my need which would be to compile temporary .o files (with gcc -c script.c for example) and can only be accessed by the PID of the current program (and destroyed once it is stopped). Do you know if that is possible ?

One of the solutions could also be to create a directory in /tmp only accessible by the program much like the systemd-private-* directories system.

the program starts like this:

#include <sys/types.h>
#include <unistd.h>

int main(int argc, char *argv[]){

    printf("pid=%d\n", getpid());
    
    /* for create .o in tmp file, but i dont know how to but
    I don't know how to create/configure "systemd-***" directory
    or if it is possible to directly create a temporary file*/
    /* the ideal would be not to have to create a special user,
    which would give rights specifically to the directory/file */
    int ret = system("gcc -c script.c -o /tmp/systemd-private-script/script.o");
    ...

    return(0);
}

Thanks for you help

1

There are 1 answers

0
Cristian Rodríguez On

On linux, yes. using open with the O_TMPFILE and O_EXCL flags, you use the posix_spawn api instead of system(). make gcc ouput to the stdout, which is connected to the open fd. After you are done close the fd and it will vanish, it can never be accessed by anyone as it is not materialized on the filesystem.