实验来自《UNIX操作系统实验教程》

实验内容:控制进程间实现互斥

用lockf函数给共享同一资源的多个进程加锁、解锁,实现进程之间的互斥。

源代码

#include <stdio.h>

#include <sys/types.h>

#include <stdlib.h>

#include <sys/wait.h>

#include <unistd.h>

#include <fcntl.h>

#include <sys/stat.h>

 

void lock(int fd);

void unlock(int fd);

void main()

{

        int fd;

        pid_t pid;

        char str[80];

        fd=open("lock.tmp",O_RDWR|O_CREAT,0644);

        if((pid=fork())==-1)

                perror("fork()");

        else if(pid>0){

                lock(fd);

                printf("I am a parent process,my pid is %d\n",getpid());

                printf("Please enter a string:\n");

                scanf("%s",str);

                lseek(fd,0L,0);

                write(fd,str,sizeof(str));

                unlock(fd);

                wait(NULL);

                close(fd);

        }

        else{

                sleep(1);

                lock(fd);

                lseek(fd,0L,0);

                char str_tmp[80];

                read(fd,str_tmp,sizeof(str));

                unlock(fd);

                printf("\nI am a child process,my pid is %d\n",getpid());

                printf("the entered string from my parent process is:%s\n",str_tmp);

        }

}

 

void lock(int fd)

{

        lseek(fd,0L,0);

        if(lockf(fd,F_LOCK,0L)==-1){

                perror("lock()");

        }

}

 

void unlock(int fd)

{

        lseek(fd,0L,0);

        if(lockf(fd,F_ULOCK,0L)==-1){

                perror("unlock()");

        }

}

 

运行结果:

[huazi@huazi ~]$ ./lockf.o 

I am a parent process,my pid is 15673

Please enter a string:

mlgb

 

I am a child process,my pid is 15674

the entered string from my parent process is:mlgb

 

总结:sleep函数起了很重要的作用。因为它确保了父进程的写先于子进程的读。