| 1 | #include <stdio.h> |
| 2 | #include <unistd.h> |
| 3 | #include <fcntl.h> |
| 4 | #include <sys/file.h> |
| 5 | |
| 6 | int main(int argc, unsigned char **argv) |
| 7 | { |
| 8 | int c; |
| 9 | int fd, locktype; |
| 10 | pid_t pid; |
| 11 | int status; |
| 12 | |
| 13 | locktype = LOCK_EX; |
| 14 | while((c = getopt(argc, argv, "se")) > 0) |
| 15 | { |
| 16 | switch(c) |
| 17 | { |
| 18 | case 's': |
| 19 | locktype = LOCK_SH; |
| 20 | break; |
| 21 | case 'e': |
| 22 | locktype = LOCK_EX; |
| 23 | break; |
| 24 | default: |
| 25 | return(1); |
| 26 | } |
| 27 | } |
| 28 | if(argc - optind < 2) |
| 29 | { |
| 30 | fprintf(stderr, "Wrong number of arguments\n"); |
| 31 | return(1); |
| 32 | } |
| 33 | if((fd = open(argv[optind], O_RDWR | O_CREAT, 0600)) < 0) |
| 34 | { |
| 35 | perror(argv[optind]); |
| 36 | return(1); |
| 37 | } |
| 38 | optind++; |
| 39 | flock(fd, locktype); |
| 40 | if((pid = fork()) < 0) |
| 41 | { |
| 42 | perror("fork"); |
| 43 | return(1); |
| 44 | } else if(!pid) { |
| 45 | execvp(argv[optind], argv + optind); |
| 46 | perror(argv[optind]); |
| 47 | exit(127); |
| 48 | } |
| 49 | while(wait(&status) != pid); |
| 50 | flock(fd, LOCK_UN); |
| 51 | return(status); |
| 52 | } |