How can I suppress following warning from gcc linker:
warning: the use of 'mktemp' is dangerous, better use 'mkstemp'
I do know that it's better to use mkstemp()
but for some reason I have to use mktemp()
function.
How can I suppress following warning from gcc linker:
warning: the use of 'mktemp' is dangerous, better use 'mkstemp'
I do know that it's better to use mkstemp()
but for some reason I have to use mktemp()
function.
If you are statically linking the runtime, then the other option is to write your own version of mktemp
in an object file. The linker should prefer your version over the runtime version.
Edit: Thanks to Jason Coco for pointing out a major misunderstanding that I had in mktemp
and its relatives. This one is a little easier to solve now. Since the linker will prefer a version in an object file, you just need to write mktemp
in terms of mkstemp
.
The only difficulties are cleaning up the file descriptors that mkstemp
will return to you and making everything thread safe. You could use a static array of descriptors and an atexit
-registered function for cleanup if you can put a cap on how many temporary files you need. If not, just use a linked list instead.
mktemp
is frequently misused when the one wants
to create a temporary name without actually creating
a tmp file, like mkstemp
would do. Maybe you want
to pass such name to sem_open
or shm_open
, and
you are well aware of an O_EXCL flag. There are many
possible uses, when you want to create some object
with a random name, and that object is not a tmp file.
However, mktemp
really should not be used, even in
that case. This is because it checks the generated
name over the existing file, and if such file exist,
it generates another name, and so on, in a loop.
This is really not what you want, especially if you
are not going to create such a file at the end.
So it would be better to just write your own
implementation targeting your specific needs, rather
than to try silencing the mktemp
warning. I simply
extracted the mktemp
generator code from glibc
sources and added the %P
modifier handling, which
adds the pid to a template:
https://github.com/dosemu2/dosemu2/blob/devel/src/base/misc/utilities.c#L1103
You can use that code as an example, or just write
your own.
There are just the basic caution rules when doing such kind of tricks:
I believe the above recommendations are sufficient
for making the use of your own mktemp
-alike function
secure and robust. But that's just my own opinion.
I guess you need the path because you pass it to a library that only accepts path names as argument and not file descriptors or
FILE
pointers. If so you can create a temp dir withmkdtemp
and place your file there, the actual name is then unimportant because the path is already unique because of the directory.