|
楼主 |
发表于 2003-4-7 22:10:28
|
显示全部楼层
continue~~
[code:1]
/* File: mutex-semaphore.c */
/* write by Zhang Yuqiang([email protected])
Computer Science of Shandong University
environment Redhat linux 9.0 with gcc3.2
2003.04.07
Good luck! */
//-----------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <linux/sem.h>
#define NUM_PROCS 5
#define SEM_ID 250
#define FILE_NAME "/tmp/sem.txt"
#define DELAY 400000
void update_file(int sem_set_id,char *file_path,int number)
{
struct sembuf sem_op;
FILE *file;
//wait for the semaphore value above or equall zero
sem_op.sem_num=0;
sem_op.sem_op=-1;
sem_op.sem_flg=0;
semop(sem_set_id,&sem_op,1);
//write the PID into file
file=fopen(file_path,"w");
if (file) {
fprintf(file,"%d\n",number);
printf("%d\n",number);
fclose(file);
}
//add the semaphore value
sem_op.sem_num=0;
sem_op.sem_op=1;
sem_op.sem_flg=0;
semop(sem_set_id,&sem_op,1);
}
//--------child process write the file--------------
void do_child_loop(int sem_set_id,char *file_name)
{
int pid=getpid();
int i,j;
for (i=0;i<3;i++){
update_file(sem_set_id,file_name,pid);
for (j=0;j<DELAY;j++);
}
}
//-----------------MAIN----------------------------
int main(int argc,char *argv[])
{
int sem_set_id; //the semaphore set's ID
union semun sem_val; //the value of semaphore
int child_pid; //the child process's ID
int i;
int rc; //return value
//create semaphore set,ID is 250,only one semaphore
sem_set_id=semget(SEM_ID,1,IPC_CREAT | 0600);
if (sem_set_id==-1){
perror("main:semget");
exit(1);
}
sem_val.val=1; //set semaphore value to 1
rc=semctl(sem_set_id,0,SETVAL,sem_val);
if (rc==-1){
perror("main:semctl");
exit(1);
}
//create some child processes.
for (i=0;i<NUM_PROCS;i++){
child_pid=fork();
switch(child_pid){
case -1:
perror("fork");
exit(1);
case 0: //implayment child process
do_child_loop(sem_set_id,FILE_NAME);
exit(0);
default: //implayment parent process
break;
}
}
//wait the child process end
for (i=0;i<NUM_PROCS;i++){
int child_status;
wait(&child_status);
}
printf("Main:We're done\n");
fflush(stdout);
return 0;
}
//-----------------------------------------------
[/code:1] |
|