- 论坛徽章:
- 95
|
我寫了一個:
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #define CNT 10
- void write_file(int fd, char data, size_t len);
- int main(int argc, char *argv[])
- {
- char *fn;
- int fd;
- pid_t pid;
- if (argc > 1)
- fn = argv[1];
- else
- fn = "flock-demo";
- if ((fd = open(fn, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
- perror("open:");
- exit(-1);
- }
- for (int i = 0; i < CNT; i++) {
- if ((pid = fork()) < 0) {
- perror("fork:");
- exit(-1);
- } else {
- if (pid == 0) {
- /* child process */
- write_file(fd, i, sizeof(i));
- exit(0);
- }
- }
- }
- return 0;
- }
- void write_file(int fd, char data, size_t len)
- {
- struct flock fl;
- /* lock the whole file */
- fl.l_whence = SEEK_SET;
- fl.l_start = 0;
- fl.l_len = 0;
- for (int i = 0; i < CNT; i++) {
- fl.l_type = F_WRLCK;
- if (fcntl(fd, F_SETLKW, &fl) < 0) {
- perror("fcntl:");
- exit(-1);
- }
- ssize_t wlen = write(fd, &data, len);
- if (wlen < 0) {
- perror("write:");
- exit(-1);
- } else {
- if ((size_t)wlen < len) {
- fprintf(stderr, "Other write error in process %d\n", getpid());
- exit(-1);
- }
- }
- fl.l_type = F_UNLCK;
- if (fcntl(fd, F_SETLKW, &fl) < 0) {
- perror("fcntl:");
- exit(-1);
- }
- }
- }
复制代码 查看結果:
- lee@debian:~/tmp/C$ gcc -std=c99 flock.c
- lee@debian:~/tmp/C$ ./a.out
- lee@debian:~/tmp/C$ od -A d -w40 -t xI -v flock-demo
- 0000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
- 0000040 00000001 00000001 00000001 00000001 00000001 00000001 00000001 00000001 00000001 00000001
- 0000080 00000002 00000002 00000002 00000002 00000002 00000002 00000002 00000002 00000002 00000002
- 0000120 00000003 00000003 00000003 00000003 00000003 00000003 00000003 00000003 00000003 00000003
- 0000160 00000004 00000004 00000004 00000004 00000004 00000004 00000004 00000004 00000004 00000004
- 0000200 00000005 00000005 00000005 00000005 00000005 00000005 00000005 00000005 00000005 00000005
- 0000240 00000006 00000006 00000006 00000006 00000006 00000006 00000006 00000006 00000006 00000006
- 0000280 00000007 00000007 00000007 00000007 00000007 00000007 00000007 00000007 00000007 00000007
- 0000320 00000008 00000008 00000008 00000008 00000008 00000008 00000008 00000008 00000008 00000008
- 0000360 00000009 00000009 00000009 00000009 00000009 00000009 00000009 00000009 00000009 00000009
- 0000400
复制代码 若要各個子進程的輸出不互相穿插,則需要把加鎖放在子進程輸出循環的外面。 |
|