文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Linux进程间通讯之信号量sem

Linux进程间通讯之信号量sem

时间:2010-12-25  来源:willwwei

信号量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;
}
分析:用于多个进程对于共享内存的存取。
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载