C 如何使用信号量同步进程
假设我有3个进程,包括一个父进程,我必须按P3,P1,P2的顺序执行程序。伙计们,请帮助我如何从P3开始计算 我需要输出为{0,1,2,3,4,5,…max} 作为参考,我的代码快照是:-C 如何使用信号量同步进程,c,operating-system,semaphore,binary-semaphore,C,Operating System,Semaphore,Binary Semaphore,假设我有3个进程,包括一个父进程,我必须按P3,P1,P2的顺序执行程序。伙计们,请帮助我如何从P3开始计算 我需要输出为{0,1,2,3,4,5,…max} 作为参考,我的代码快照是:- #define SEM_NAME "//test.mutex" //#define SEM_NAME2 "//test2.mutex" int main(int argc, char const *argv[]) { int max = 0, i =0; sem_t *sem; sem_t *
#define SEM_NAME "//test.mutex"
//#define SEM_NAME2 "//test2.mutex"
int main(int argc, char const *argv[]) {
int max = 0, i =0;
sem_t *sem;
sem_t *sem2;
pid_t pid, pid2;
sem = sem_open(SEM_NAME, O_CREAT, O_RDWR, 1);
sem_unlink(SEM_NAME);
if (sem==SEM_FAILED) {
printf("%s sem_open failed!", SEM_NAME);
return (-1);
}
// sem2 = sem_open(SEM_NAME2, O_CREAT, O_RDWR, 0);
// sem_unlink(SEM_NAME2);
// if (sem2==SEM_FAILED) {
// printf("%s sem_open failed!", SEM_NAME2);
// return (-1);
// }
printf("Enter the maximum number\n");
scanf("%d", &max);
pid = fork();
if(pid == 0)
{
i = 2;
pid2 = fork();
if(pid2 == 0)
{
i = 0;
}
else
{
sleep(2);
}
}
else
{
i = 1;
sleep(1);
}
//do
{
sem_wait(sem);
for (; i <= max;) {
printf("pid %d done and value is %d\n", getpid(),i);
i = i + 3;
}
sem_post(sem);
} //while(i <= max);
wait(NULL);
return 0;
}
#定义SEM_名称”//test.mutex“
//#定义SEM_NAME2”//test2.mutex“
int main(int argc,char const*argv[]{
int max=0,i=0;
sem_t*sem;
sem_t*sem2;
pid_t pid,pid 2;
sem=sem_open(sem_NAME,O_create,O_RDWR,1);
sem_取消链接(sem_名称);
如果(sem==sem_失败){
printf(“%s sem\u open failed!”,sem\u NAME);
返回(-1);
}
//sem2=sem_open(sem_NAME2,O_create,O_RDWR,0);
//sem_取消链接(sem_名称2);
//如果(sem2==SEM_失败){
//printf(“%s sem\u open failed!”,sem\u NAME2);
//返回(-1);
// }
printf(“输入最大数字\n”);
扫描频率(“%d”和最大值);
pid=fork();
如果(pid==0)
{
i=2;
pid2=fork();
如果(pid2==0)
{
i=0;
}
其他的
{
睡眠(2);
}
}
其他的
{
i=1;
睡眠(1);
}
//做
{
sem_wait(sem);
对于(;i这里是如何实现顺序P3、P1、P2的伪代码
//semaphores for P1, P2, P3 respectively
semaphore s1=0;
semaphore s2=0;
semaphore s3=1; //coz P3 needs to go first
//for p3
wait(s3)
//do p3 here
signal(s1) //signal for P1 to start
//for p1
wait(s1)
//do p1
signal(s2) // signal to start P2
//for p2
wait(s2)
//do p2
signal(s3) //signal to start p3 again if that is required or you can omit this if not required