/* Ensure exclusive access to a file by a pipeline*/ /* Usage: yada yada|exclusive >output_file or: yada yada|exclusive name_of_file|yada name_of_file WARNING: Do not provide exclusive access to more than one file per pipeline, for risk of deadly embraces between processes. */ /*Started: RJ Botting, Sep 1999 SunOS ftp 4.1.3_U1 2 sun4m */ #include #include #include #include #include /*flock - apply or remove an advisory lock on an open file*/ main( argc, argv) int argc; char *argv[]; { int ch; int locker; /* file descriptor */ int fl;/*reponse from flock(...)*/ locker=1; /*stdout, default, allows exclusive >file */ if(argc>1){ /*fprintf(stderr, "DBUG1: %s\n",argv[1]);*/ locker=open(argv[1], O_RDONLY); if( -1 == locker){ fprintf(stderr, "File %s couldn't be openned.\n", argv[1]); perror(""); exit(1); } } fl=flock( locker, LOCK_EX); /*if(argc>1)fprintf(stderr, "DBUG2: %s %d\n",argv[1], fl);*/ /*copy stdin to stdout. From Kernighan & Ritchie Chapter 7 */ while((ch=getc(stdin))!=EOF){ putc(ch, stdout); }/*end while*/ flock( locker, LOCK_UN); if(argc>1){ /*fprintf(stderr, "DBUG3: %s\n",argv[1]);*/ close(locker); } }