Linux _sem 信号量 V_P
main1.c
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int i;
for (i=0; i<5; i++) {
/* ƒ£ƒ‚¡ŸΩÁ«¯----begin */
printf("Process(%d) In\n", getpid());
sleep(1);
printf("Process(%d) Out\n", getpid());
/* ƒ£ƒ‚¡ŸΩÁ«¯----end */
sleep(1);
}
return 0;
}
main2.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdlib.h>
#include <stdio.h>
#if defined(__GNU_LIBRARY__) && !defined(_SEM_SEMUN_UNDEFINED)
#else
union semun {
int val;
struct semid_ds *buf;
unsigned short int *array;
struct seminfo *__buf;
};
#endif
static sem_initial(int semid)
{
int ret;
union semun semun;
semun.val = 1;
ret = semctl(semid, 0, SETVAL, semun);
if (ret == -1) {
fprintf(stderr, "semctl failed!\n");
}
return ret;
}
static int sem_p(int semid)
{
int ret;
struct sembuf sembuf;
sembuf.sem_op = -1;
sembuf.sem_num = 0;
sembuf.sem_flg = SEM_UNDO;
ret = semop(semid, &sembuf, 1);
if (ret == -1) {
fprintf(stderr, "sem_p failed!\n");
}
return ret;
}
static int sem_v(int semid)
{
int ret;
struct sembuf sembuf;
sembuf.sem_op = 1;
sembuf.sem_num = 0;
sembuf.sem_flg = SEM_UNDO;
ret = semop(semid, &sembuf, 1);
if (ret == -1) {
fprintf(stderr, "sem_v failed!\n");
}
return ret;
}
int main(int argc, char* argv[])
{
int i;
int ret;
int semid;
/* ªÒ»°–≈∫≈¡ø */
semid = semget((key_t)1234, 1, 0666 | IPC_CREAT);
if (semid == -1) {
printf("semget failed!\n");
exit(1);
}
/* ≥ı ºªØ–≈∫≈¡ø */
if (argc > 1) {
ret = sem_initial(semid);
if (ret == -1) {
exit(1);
}
}
for (i=0; i<5; i++) {
if (sem_p(semid) == -1) {
exit(1);
}
/* ƒ£ƒ‚¡ŸΩÁ«¯----begin */
printf("Process(%d) In\n", getpid());
sleep(1);
printf("Process(%d) Out\n", getpid());
/* ƒ£ƒ‚¡ŸΩÁ«¯----end */
if (sem_v(semid) == -1) {
exit(1);
}
sleep(1);
}
/* …æ≥˝–≈∫≈¡ø */
return 0;
}