• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 564
  • Last Modified:

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 ?
0
smiththomasg
Asked:
smiththomasg
1 Solution
 
prakashagrCommented:
Hi smiththomasg

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

system( " rm  fifoname");

Prakash
0
 
prakashagrCommented:
$ mkfifo fifoname


ex:

main() {

int fd;
fd = open("fifoname" 666);
close(fd);
system("rm fifoname");
}
0
 
madhurdixitCommented:
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.

0
 
smiththomasgAuthor Commented:
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().
0
 
moduloCommented:
Closed, 125 points refunded.

modulo
Community Support Moderator
Experts Exchange
0

Featured Post

Live webcast with Pinal Dave

Pinal Dave will teach you tricks to help identify the real root cause of database problems rather than red herrings. Attendees will learn scripts that they can use in their environment to immediately figure out their performance Blame Shifters and fix them quickly.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now