#include #include #include #include #include #include void make_fifo_if_not_exists(char *fifo_name) { struct stat s; // stat is a function that returns information about a file (if it exists) -> see man 2 stat // we will check the owner and file type from here // if we don't own the file -> abort // if file is not a FIFO -> abort // if it is a FIFO and we own it -> try to unlink and remake FIFO to ensure that it is empty. if(0 > stat(fifo_name, &s)) { // ENOENT -> file doesn't exist // We can try to create a FIFO with that name if(ENOENT == errno) { printf("No file with the name %s exists, we're good to go.\n", fifo_name); if(0 > mkfifo(fifo_name, 0600)) { perror("Error on creating fifo: "); exit(1); } } else { // other error encountered // best to abort here perror("Error encountered while trying to get info about the filename: "); exit(1); } } else { // we found a file with the given name, let's check who owns it and what type of file it is if (s.st_uid == getuid()) { // if we are the owner of the file // S_ISFIFO is a macro described in the manual page of stat (man 2 stat) // it uses the st_mode field of the stat structure to identify the type if(S_ISFIFO(s.st_mode)) { printf("FIFO %s already exists. Trying to unlink and remake.\n", fifo_name); // file is a FIFO and we own it // let's remake it to clean it up if(0 > unlink(fifo_name)) { perror("Unable to remove fifo: "); exit(1); } if(0 > mkfifo(fifo_name, 0600)) { perror("Error on creating fifo: "); exit(1); } } else { // if not a FIFO, leave it alone and abort printf("File %s exists and is not a FIFO.\n", fifo_name); } } else { // we are not the owner of the file, it's best to leave it alone printf("The file %s belongs to somebody else.", fifo_name); exit(1); } } } int main(int argc, char *argv[]) { make_fifo_if_not_exists("./myfifo"); return 0; }