lockf( fd, mode, size );this
mode 爲 1 時表示加鎖,爲 0 時表示解鎖。spa
#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> #include<stdlib.h> int main() { pid_t pid; int retval; char buf[6] = "hello"; if( (pid = fork() )< 0 ) { printf("fork error\n"); exit(-1); } else if( pid == 0 ) { while(1) { if( lockf(1,1,0) < 0 ) { printf("lockf on error\n"); exit(-1); } sleep(1); printf("this is in child!\n"); sleep(1); printf("this is in child!\n"); if( lockf(1,0,0) <0 ) { printf("lockf off error\n"); exit(-1); } sleep(1); } printf("this is child end\n"); exit(-1); } //wait(&retval); while(1) { if( lockf(1,1,0) < 0 ) { printf("lockf on error\n"); exit(-1); } sleep(1); printf("this is in parent!\n"); sleep(1); printf("this is in parent!\n"); if( lockf(1,0,0) <0 ) { printf("lockf off error\n"); exit(-1); } sleep(1); } printf("this is parent process end\n"); return 0; }