- 论坛徽章:
- 0
|
回复 #4 风之幻想 的帖子
这是源程序,帮忙看看吧 "unpipc.h"是一个杂凑的头文件
#include <sys/sem.h>
#include <synch.h>
#include <semaphore.h>
#include <sys/wait.h>
#include <errno.h>
#include "unpipc.h"
int count = 0;
int main(int argc, char** argv)
{
int i, nloop;
sem_t* mutex;
char* SEM_NAME = "mysem";
if(argc != 2){
err_quit("usage: incr1<#loops>");
}
printf("please input a number\n");
nloop = atoi(argv[1]);
mutex = sem_open(SEM_NAME, O_CREAT | O_EXCL | FILE_MODE, 1);
sem_unlink(SEM_NAME);
setbuf(stdout, NULL);
if(fork() == 0){
for(i = 0; i < nloop; i++){
sem_wait(mutex);
printf("child: %d\n", count++);
sem_post(mutex);
}
_exit(0);
}
for(i = 0; i < nloop; i++){
sem_wait(mutex);
printf("parent: %d\n", count++);
sem_post(mutex);
}
exit(0);
} |
|