Linux进程间通讯之信号量sem

信号量sem:
willisway1:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#define NR  100
#define SIZE 1024
static int semid;
int sem_init(void)
{
    int arg;
    semid = semget(IPC_PRIVATE, 1, IPC_CREAT | 0600);
    arg = 1;
    semctl(semid, 0, SETVAL, arg);
    return 0;
}
int sem_destroy(void)
{
    return semctl(semid, 0, IPC_RMID);
}
int sem_lock(void)
{
    struct sembuf dec = {
                      .sem_num = 0,
                      .sem_op = -1,
                      .sem_flg = SEM_UNDO
                        };
    semop(semid, &dec, 1);
}
int sem_unlock(void)
{
    struct sembuf inc = {
                      .sem_num = 0,
                      .sem_op = 1,
                      .sem_flg = SEM_UNDO
                        };
    semop(semid, &inc, 1);
}
int main(void)
{
    pid_t pid;
    int i, ret;
    int fd, num;
    char buf[SIZE];
    sem_init();
    fd = open("./test", O_RDWR | O_CREAT, 0600);
    for (i = 0; i < NR; ++i)
    {
        pid = fork();
        if (pid == 0)
        {
            ret = sem_lock();
            lseek(fd, 0, SEEK_SET);
            ret = read(fd, buf, SIZE);
            usleep(1);
            buf[ret] = '/0';
            num = atoi(buf);
            num += 1;
            snprintf(buf, SIZE, "%d", num);
            lseek(fd, 0, SEEK_SET);
            usleep(1);
            ret = write(fd, buf, strlen(buf));
            fsync(fd);
            usleep(1);

            ret = sem_unlock();
            exit(0);
        }
    }
    for (i = 0; i < NR; ++i)
    {
        wait(NULL);
    }
    close(fd);
    sem_destroy();
    return 0;
}
分析:用于多个进程对于共享内存的存取。

你可能感兴趣的:(Linux进程间通讯之信号量sem)