如何为父母和子女的信号量操作完成子进程?

时间:2017-05-08 08:21:26

标签: process synchronization fork shared-memory semaphore

如果semget调用共享父进程和子进程之间的信号量? 我有这个代码,并且对于相同的代码,我观察到如果父运行第一个,子进程有时会获得更改的信号量值,但是当子进程首先运行时,父进程似乎永远不会继续执行更改的信号量。 为什么会这样?有人可以向我解释这件事吗?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <math.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>

 int main() {


int semid = semget(12, 2, 0666|IPC_CREAT);
int status;



semctl(semid, 0, SETVAL, 12);
semctl(semid, 1, SETVAL, 1);

short int outarray[2], last;
char output[200];
struct sembuf obj1[] = { {0, -1, SEM_UNDO}, {1, -1, SEM_UNDO} };
struct sembuf obj2[] = { {0, 0, SEM_UNDO}, {1, 0, SEM_UNDO} };
struct sembuf obj3[] = { {0, 1, SEM_UNDO}, {1, 1, SEM_UNDO} };

int pid = fork();
//wait(&status);    

    semctl(semid, 2, GETALL, outarray);
    printf("OUT(%d):%d %d %d\n", getpid(),outarray[0], outarray[1], last);
if(pid!=0) {

    printf("Semid Parent:%d\n",semid);

    semctl(semid, 2, GETALL, outarray);
    printf("%d %d %d\n", outarray[0], outarray[1], last);
    printf("Parent Check1\n");
    last = semop(semid, obj1, 2);
    semctl(semid, 2, GETALL, outarray);
    printf("%d %d %d\n", outarray[0], outarray[1], last);
    printf("Parent Check2\n");
    last = semop(semid, obj2, 2);
    semctl(semid, 2, GETALL, outarray);
    printf("%d %d %d\n", outarray[0], outarray[1], last);
    printf("Parent Check3\n");
    //sleep(10);

}
else {

    semctl(semid, 2, GETALL, outarray);
    printf("Child: %d %d %d\n", outarray[0], outarray[1], last);
    //leep(2);
    printf("Semid Child:%d\n",semid);
    int x;
    printf("Child Check1\n");
    last = semop(semid, obj1, 2);
    semctl(semid, 2, GETALL, outarray);
    printf("child %d %d %d\n", outarray[0], outarray[1], last);
    //sleep(2);
    printf("Child Check2\n");
    last = semop(semid, obj3, 2);
    semctl(semid, 2, GETALL, outarray);
    printf("child %d %d %d\n", outarray[0], outarray[1], last);
    //sleep(2);
    printf("Child Check3\n");
    last = semop(semid, obj1, 2);
    semctl(semid, 2, GETALL, outarray);
    printf("child %d %d %d\n", outarray[0], outarray[1], last);
    //sleep(2);
    printf("Child Check4\n");
    //sleep(10);
    semctl(semid, 2, GETALL, outarray);
    printf("child %d %d %d\n", outarray[0], outarray[1], last);
    semctl(semid, 2, GETNCNT, x);
    printf("%d\n",x);

    sleep(5);
}

return 0;
}

输出:

这是父项首次运行时的输出

OUT(3167):12 1 0
Semid Parent:0
12 1 0
Parent Check1
11 0 0
Parent Check2

OUT(3168):12 1 0
Child: 11 0 0
Semid Child:0
Child Check1

这是子项首先运行时的输出。我在if循环中添加了一个等待

OUT(3679):12 1 0
OUT(3680):12 1 0
Child: 12 1 0
Semid Child:0
Child Check1
child 11 0 0
Child Check2
child 12 1 0
Child Check3
child 11 0 0
Child Check4
child 11 0 0
0

Semid Parent:0
12 1 0
Parent Check1
11 0 0
Parent Check2

0 个答案:

没有答案