#include#include #include #include #include union semun{ int val; struct semid_ds *buf; unsigned short *array; struct seminfo *__buf; }; void pGetKey(int id) { struct sembuf set; set.sem_num = 0;// set.sem_op = -1; set.sem_flg = SEM_UNDO; semop(id,&set,1); printf("getKEYn"); } void vPutBack(int id) { struct sembuf set; set.sem_num = 0; set.sem_op = 1; set.sem_flg = SEM_UNDO; semop(id,&set,1); printf("Put back Keyn"); } int main(int argc,char **argv) { key_t key; int semid; key = ftok(".",2); semid = semget(key,1,IPC_CREAT|0666);//获取/创建信号量 union semun initsem; initsem.val = 0;//锁 semctl(semid,0,SETVAL,initsem);//初始化信号量 int pid = fork(); if(pid > 0){ //去拿锁 pGetKey(semid);//拿钥匙 printf("This is fathern"); vPutBack(semid);//放钥匙 semctl(semid,0,IPC_RMID); }else if(pid == 0){ printf("This is childn"); vPutBack(semid); }else{ printf("create errorn"); } return 0; }
通过上边的代码运行后,就能确保子进程比父进程先运行,通过信号量来控制。
函数原型:NAME
semop, semtimedop - System V semaphore operations
SYNOPSIS
#include
#include
#include
int semop(int semid, struct sembuf *sops, size_t nsops);
int semtimedop(int semid, struct sembuf *sops, size_t nsops,
const struct timespec *timeout);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
semtimedop(): _GNU_SOURCE
DEscriptION
Each semaphore in a System V semaphore set has the following associated values:
unsigned short semval;
unsigned short semzcnt;
unsigned short semncnt;
pid_t sempid;
short sem_op;
short sem_flg;
Flags recognized in sem_flg are IPC_NOWAIT and SEM_UNDO. If an operation specifies SEM_UNDO, it will be automatically undone when the process terminates.
NAME
semctl - System V semaphore control operations
SYNOPSIS
#include
#include
#include
int semctl(int semid, int semnum, int cmd, ...);
DEscriptION
semctl() performs the control operation specified by cmd on the System V semaphore set identified by semid, or on the semnum-th semaphore of that set. (The semaphores in a set are numbered starting at 0.)
This function has three or four arguments, depending on cmd. When there are four, the
fourth has the type union semun. The calling program must define this union as follows:
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
struct seminfo *__buf;
};
The semid_ds data structure is defined in as follows:
struct semid_ds {
struct ipc_perm sem_perm;
time_t sem_otime;
time_t sem_ctime;
unsigned long sem_nsems;
};
运行结果:



