- #include <sys/wait.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <stdio.h>
- #include <string.h>
- #include <fcntl.h>
- #include <stdlib.h>
- int main(){
- //int i;
- int commonfile = open("commonfile",O_RDWR | O_CREAT | O_TRUNC , 0666);
- //pid_t pid[5];
- struct flock f;
- f.l_type = F_WRLCK;
- f.l_start = 0;
- f.l_whence = SEEK_SET;
- f.l_len = 0;
- f.l_pid = getpid();
- printf("here0\n");
- printf("%d\n",fcntl(commonfile,F_SETLK,&f));
- //write(commonfile,buffer,strlen(buffer));
- printf("here\n");
- //struct flock f2;
- f.l_type = F_UNLCK;
- //f2.l_start = 0;
- //f2.l_whence = SEEK_SET;
- //f2.l_len = 0;
- //f2.l_pid = getpid();
- printf("%d\n",fcntl(commonfile,F_SETLK,&f));
- struct flock f3;
- f3.l_type = F_WRLCK;
- f3.l_start = 0;
- f3.l_len = 0;
- f3.l_whence = SEEK_SET;
- f3.l_pid = getpid();
- printf("%d\n",fcntl(commonfile,F_SETLK,&f3));
- printf("here2\n");
- /*
- for(i=0;i<5;i++){
- pid[i] = fork();
- if(pid[i]==0){
- int j=0;
- char buffer[100];
- for(j=0;j<10;j++){
- sprintf(buffer,"this is process no %d print no %d\n",getpid(),j);
- struct flock f;
- f.l_type = F_WRLCK;
- f.l_start = 0;
- f.l_whence = SEEK_SET;
- f.l_len = 0;
- f.l_pid = getpid();
- fcntl(commonfile,F_SETLKW,&f);
- //write(commonfile,buffer,strlen(buffer));
- printf("here\n");
- struct flock f2;
- f2.l_type = F_UNLCK;
- f2.l_start = 0;
- f2.l_whence = SEEK_SET;
- f2.l_len = 0;
- f2.l_pid = getpid();
- fcntl(commonfile,F_SETLKW,&f2);
- //int commonfile2 = open("commonfile",O_WRONLY | O_APPEND,00777);
- //write(commonfile,buffer,strlen(buffer));
- }
- exit(0);
- }
- }
- int status[5];
- for(i=0;i<5;i++){
- waitpid(pid[i],&status[i],0);
- }
- */
- //printf("commonfile descriptor = %d\n",commonfile);
- }
Raw Paste