Link to home
Start Free TrialLog in
Avatar of smiththomasg
smiththomasg

asked on

Automatically delete a FIFO

A unix 'C' program opens a named pipe (FIFO) with 'mkfifo'.  Upon normal exit (or system crash, or "kill -9"), I would like the file to be automatically deleted.
Using "tmpfile" doesn't sound like it would work.  Could always register a routine with "atexit" but that would not work with abnormal terminations.
Looks to be like this should be the normal behavior of a named pipe anyway.  When a file reaches a use count of '0' what good is it to leave it around ?
Avatar of prakashagr
prakashagr
Flag of India image

Hi smiththomasg

In  normal termination of program u can use statement this at the end of program

system( " rm  fifoname");

Prakash
$ mkfifo fifoname


ex:

main() {

int fd;
fd = open("fifoname" 666);
close(fd);
system("rm fifoname");
}
Avatar of madhurdixit
madhurdixit

In case of abnormal termination or any other signal sent to program , you can handle those signals.

try
>man signal

Unfortunately , as far as I know,the signals corresponding to abnormal termination of program : SIGKILL and SIGSTOP (refer man page) ,
cannot be caught or ignored.

So , to do something when there is abnormal termination  is rather impossible . But yes, for other cases, you can use this.

Avatar of smiththomasg

ASKER

Here is the answer.
The key is to unlink() the file (or fifo) immediately after opening it.
The file can be read and written as long as the file is open.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main()
{
int fdTmp;
char szName[32],szTmp[512],*pszLine="Now is the time...";

strncpy(szName,"/tmp/_file_XXXXXX",sizeof(szName));
fdTmp=mkstemp(szName);

/* The file is deleted upon close */
unlink(szName);

write(fdTmp,pszLine,strlen(pszLine));
lseek(fdTmp,0L,SEEK_SET);
memset(szTmp,'\0',sizeof(szTmp));
read(fdTmp,szTmp,sizeof(szTmp));
fprintf(stdout,"Line: {%s}",szTmp);

/* If system crashes or a kill -9 is done here, the file is gone. */
fgetc(stdin);

close(fdTmp);
}

The same strategy should work with mkfifo().
ASKER CERTIFIED SOLUTION
Avatar of modulo
modulo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial