天天看點

Linux多程序程式設計(2)簡介程序的信号量機制程序間共享記憶體

簡介

IPC(Inter Process Communication,程序間通信)的方式總共有三種,分别是信号量、共享記憶體和消息隊列,本文介紹前兩種。

在Linux中,程序之間操作公共資料時,需要進行互斥操作,這種情況需要臨界區。在《Linux高性能伺服器程式設計》這本書中,給出了

semget

semop

semctl

三個函數進行有關的操作。但是,Linux官方不建議使用這三個舊的函數了,而是建議使用新的API;上述三個函數是針對有名字類型的信号量進行操作,有些情況下,還需要對公共記憶體區進行操作,此時需要無名類型的信号量,同樣的,使用官方建議的新版的API。

程序的信号量機制

PV原語操作

信号量機制和PV原語操作,是程序互斥的基礎。PV原語操作是指任意時刻任何程序或者線程隻能通過PV原語對信号量進行操作,操作是原子的,不能有其他程序中斷目前程序的操作。

假設有信号量S,V操作是

S = S + 1

, P操作是

S = S - 1

;如果

S = 0

,V操作阻塞,等待其他程序喚醒。最典型的應用是生産者消費者模型,生産者進行P操作,消費者V操作。

PV原語對應Linux的系統調用

在Linux中,

sem_t

類型表示一個信号量,是一個特有的資料類型。

V操作對應的函數

#include <semaphore.h>
int sem_post(sem_t* sem);
           

需要添加

-pthread

連接配接。

sem

是信号量值,該函數使得

sem

加1,如果加1後

*sem > 0

而且有程序阻塞,那麼會喚醒阻塞的程序。成功傳回0,失敗傳回-1。

P操作對應的函數

#include <semaphore.h>
int sem_wait(sem_t* sem);
           

如果sem指向的信号量大于0,那麼

*sem -= 1

,而且會立刻傳回,如果目前

*sem == 0

,那麼會阻塞,有可能使得信号量-1。

有名信号量和無名信号量差別與聯系

兩者都是信号量機制的,用于消息傳遞和互斥。

無名信号量隻能存在于記憶體中,要求使用信号量的程序必須能通路信号量所在的這一塊記憶體,是以無名信号量隻能應用在同一程序内的線程之間(共享程序的記憶體),或者不同程序中已經映射相同記憶體内容到它們的位址空間中的線程(即信号量所在記憶體被通信的程序共享)。意思是說無名信号量隻能通過共享記憶體通路。

有名信号量可以通過名字通路,是以可以被任何知道它們名字的程序中的線程使用。

單個程序中使用 POSIX 信号量時,無名信号量更簡單。多個程序間使用 POSIX 信号量時,有名信号量更簡單。

作者:ACool

連結:https://juejin.im/post/5b2908d2e51d4558e3600827

來源:掘金

著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。

有名信号量執行個體

關于建立多個子程序,參考這篇部落格:https://blog.csdn.net/qq_35976351/article/details/86584644

建立函數:

#include <fcntl.h>           /* For O_* constants */
#include <sys/stat.h>        /* For mode constants */
#include <semaphore.h>

sem_t *sem_open(const char *name, int oflag);
sem_t *sem_open(const char *name, int oflag,
                mode_t mode, unsigned int value);
           

name

是信号量的名稱,如果

oflag

O_CREAT

,而且是第一次建立,則必須使用第二個函數,

mode

表示去權限,

value

是信号量的初始值;如果同樣的

oflag

,已經存在,則使用第一個。

代碼執行個體,父子程序使用信号量同步,父程序不使用

wait

函數。

#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/stat.h>

sem_t* sem;
const char* sem_name = "my_sem";

int main() {
    sem = sem_open (sem_name, O_CREAT, 0660, 0);

    int pid = fork();
    if (pid < 0) {
        perror ("fork() error\n");
        return 1;
    } else if (pid == 0) {  // 子程序
        sleep (3); // 續3秒
        puts ("child");
        sem_post (sem);
    } else {  // 父程序
        sem_wait (sem);
        puts ("parent");
        sem_destroy(sem);
    }

    return 0;
}
           

無名信号量執行個體

無名信号的建立函數:

#include <semaphore.h>
int sem_init(sem_t* sem, int pshared, unsigned int value);
           

sem

是信号量位址。

pshared

是共享的标志,如果為0,表示一個程序内各個線程之間共享;不為零表示程序之間的共享。成功傳回0,失敗傳回-1。

該函數需要和共享記憶體的程序共同使用,因為

sem

參數必須是在 共享記憶體上的。

程序間共享記憶體

這一部分指的是無名的信号量,即共享記憶體。

建立共享記憶體:

#include <sys/shm.h>
int shmget(key_t key, size_t size, int shmflg);
           
  • key

    :一個鍵值,表示全局唯一的共享記憶體
  • size

    :共享記憶體的大小,機關是位元組
  • shmflg

    :一個标記,一般設定為

    O_CREAT

    ,具體查手冊。這裡說明兩個特殊的:
    • SHM_HUGETLB

      :系統使用大頁面為共享記憶體配置設定空間
    • SHM_NORESERVE

      :不為共享記憶體保留交換分區

函數成功傳回正整數值,是共享記憶體的辨別符;失敗傳回-1。

共享記憶體建立完畢,需要先關聯到程序的位址空間中;使用完畢後,也需要将它從程序位址空間中分離。調用如下兩個函數:

#include <sys/shm.h>
void* shmat(int shm_id, const void* shm_addr, int shmflg);  // 關聯函數
int shmdt(const void* shm_addr);  // 分離函數
           
  • shm_id

    :由

    shmget

    傳回的共享記憶體辨別符
  • shm_addr

    :如果是

    NULL

    ,關聯的位址由作業系統決定,推薦這麼做;非空的情況比較複雜,查找手冊即可。

系統使用

shmctl

操作共享記憶體的屬性,具體參考手冊。

#include <sys/shm.h>
int shmctl(int shm_id, int command, struct shmid_ds* buf);
           

共享記憶體的POSIX方法:

#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
int shm_open(const char* name, int oflag, mode_t mode);
int shm_unlink(const char* name);
           

類似于

mmap

方法,不過這裡是具名共享記憶體。

name

是共享記憶體的名稱,

oflag

是建立方式,具體參照手冊,成功傳回檔案描述符,失敗傳回-1。第二個是取消連接配接,

name

同上。

共享記憶體的多程序聊天室代碼執行個體:

#include <sys/shm.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

#define USER_LIMIT 32
#define BUFFER_SIZE 1024
#define FD_LIMIT 65535
#define MAX_EVENT_NUMBER 1024
#define PROCESS_LIMIT 65536

struct client_data {
    sockaddr_in address; // 用戶端位址
    int connfd;          // socket檔案描述符
    pid_t pid;           // 用戶端程序的pid
    int pipefd[2];       // 和父程序通信的管道
};

static const char* shm_name = "my_shm";
int sig_pipefd[2];
int epollfd = -1;
int listenfd = -1;
int shmfd = -1;
char* share_mem = 0;
client_data* users = 0;  // 客戶連接配接資料,程序客戶連接配接的來索引資料
int* sub_process;  // 子程序和客戶連接配接的映射關系表,用程序的pid縮影這個數組
int user_count = 0;  // 目前客戶的數量
bool stop_child = false;

int setnonblocking (int fd) {
    int old_option = fcntl (fd, F_GETFL);
    int new_option = old_option | O_NONBLOCK;
    assert (fcntl (fd, F_SETFL, new_option) != -1);
    return old_option;
}

void addfd (int epollfd, int fd) {
    epoll_event event;
    bzero (&event, sizeof (event) );
    event.data.fd = fd;
    event.events |= EPOLLIN | EPOLLET;
    assert (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, &event) != -1);
    setnonblocking (fd);
}

void sig_handler (int sig) {
    int save_errno = errno;
    int msg = sig;
    send (sig_pipefd[1], (char*) &msg, sizeof (char), 0);
    errno = save_errno;
}

void addsig (int sig, void (*handler) (int), bool restart = true) {
    struct sigaction sa;
    bzero (&sa, sizeof (sa) );
    sa.sa_handler = handler;
    if (restart) {
        sa.sa_flags |= SA_RESTART;
    }
    sigfillset (&sa.sa_mask);
    assert (sigaction (sig, &sa, NULL) != -1);
}

void del_resource() {
    close (sig_pipefd[0]);
    close (sig_pipefd[1]);
    close (listenfd);
    close (epollfd);
    shm_unlink (shm_name);
    delete[] users;
    delete[] sub_process;
}

// 停止一個子程序
void child_term_handler (int sig) {
    stop_child = true;
}

// 子程序運作的函數,idx指出子程序處理的客戶連接配接的編号,
// users儲存客戶連接配接資料的數組
// share_mem支援共享記憶體的起始位址
int run_child (int idx, client_data* users, char* share_mem) {
    epoll_event events[MAX_EVENT_NUMBER];
    memset (events, 0, sizeof (events) );
    // 子程序IO複用同時監聽兩個檔案描述符,
    // 分别是客戶連接配接socket和與父程序通信的管道檔案描述符
    int child_epollfd = epoll_create1 (0);
    assert (child_epollfd != -1);
    int connfd = users[idx].connfd;
    int pipefd = users[idx].pipefd[1];
    addfd (child_epollfd, pipefd);
    int ret;
    addsig (SIGTERM, child_term_handler, false);

    while (!stop_child) {
        int number = epoll_wait (child_epollfd, events, MAX_EVENT_NUMBER, -1);
        if (number < 0) {
            perror ("epoll failure\n");
            break;
        }

        for (int i = 0; i < number; ++i) {
            auto sockfd = events[i].data.fd;
            auto event = events[i].events;
            if (sockfd == connfd && event & EPOLLIN) {
                memset (share_mem + idx * BUFFER_SIZE, 0, BUFFER_SIZE);
                ret = recv (connfd, share_mem + idx * BUFFER_SIZE, BUFFER_SIZE - 1, 0);
                if (ret < 0) {
                    if (errno != EINTR) {
                        stop_child = true;
                    }
                } else if (ret == 0) {
                    stop_child = true;
                } else {
                    // 通知主程序處理資料
                    send (pipefd, (char*) &idx, sizeof (idx), 0);
                }
            } else if (sockfd == pipefd && event & EPOLLIN) {
                int client = 0;
                ret = recv (sockfd, (char*) &client, sizeof (client), 0);
                if (ret < 0) {
                    if (errno != EAGAIN) {
                        stop_child = true;
                    }
                } else if (ret == 0) {
                    stop_child = true;
                } else {
                    send (connfd, share_mem + client * BUFFER_SIZE, BUFFER_SIZE, 0);
                }
            } else {
                continue;
            }
        }
    }

    close (connfd);
    close (pipefd);
    close (child_epollfd);
    return 0;
}

int main (int argc, char* argv[]) {
    if (argc != 2) {
        perror ("Usage: %s <port> of server\n");
        return 1;
    }

    int port = atoi (argv[1]);
    if (port < 1024 || port > 65535) {
        perror ("port error\n");
        return 1;
    }

    struct sockaddr_in address;
    bzero (&address, sizeof (address) );
    address.sin_family = AF_INET;
    address.sin_port = htons (port);
    address.sin_addr.s_addr = htonl (INADDR_ANY);

    listenfd = socket (AF_INET, SOCK_STREAM, 0);
    if (listenfd < 0) {
        perror ("socket() error\n");
        return 1;
    }
    setnonblocking (listenfd); // 非阻塞監聽

    int ret = bind (listenfd, (struct sockaddr*) &address, sizeof (address) );
    if (ret < 0) {
        perror ("bind() error\n");
        close (listenfd);
        return 1;
    }

    ret = listen (listenfd, 32);
    if (ret < 0) {
        perror ("listen() error\n");
        return 1;
    }

    user_count = 0;
    users = new client_data[USER_LIMIT + 1];
    sub_process = new int[PROCESS_LIMIT];
    memset (users, -1, USER_LIMIT * sizeof (int) );
    memset (sub_process, -1, PROCESS_LIMIT * sizeof (int) );

    epoll_event events[MAX_EVENT_NUMBER];
    memset (events, 0, sizeof (events) );
    epollfd = epoll_create1 (0);
    if (epollfd < 0) {
        perror ("epoll_create1() error\n");
        close (listenfd);
        return 1;
    }
    addfd (epollfd, listenfd);

    ret = socketpair (AF_UNIX, SOCK_STREAM, 0, sig_pipefd);
    if (ret < 0) {
        perror ("sockerpair() error\n");
        close (epollfd);
        close (listenfd);
        return 1;
    }
    setnonblocking (sig_pipefd[1]);
    addfd (epollfd, sig_pipefd[0]);

    addsig (SIGCHLD, sig_handler);
    addsig (SIGTERM, sig_handler);
    addsig (SIGINT, sig_handler);
    addsig (SIGPIPE, sig_handler);

    bool stop_server = false;
    bool terminate = false;

    shmfd = shm_open (shm_name, O_CREAT | O_RDWR, 0666);
    if (shmfd < 0) {
        perror ("shm_open() error\n");
        close (epollfd);
        close (listenfd);
        return 1;
    }

    share_mem = (char*) mmap (NULL, USER_LIMIT * BUFFER_SIZE, PROT_READ |
                              PROT_WRITE, MAP_SHARED, shmfd, 0);
    if (share_mem == MAP_FAILED) {
        perror ("share_mem() error\n");
        close (epollfd);
        close (listenfd);
        close (shmfd);
        return 1;
    }

    while (!stop_server) {
        int number = epoll_wait (epollfd, events, MAX_EVENT_NUMBER, -1);
        if (number < 0 && errno != EINTR) {
            perror ("epoll_wait() error\n");
            break;
        }

        for (int i = 0; i < number; ++i) {
            auto sockfd = events[i].data.fd;
            auto event = events[i].events;
            if (sockfd == listenfd) {
                struct sockaddr_in client_address;
                bzero (&address, sizeof (address) );
                socklen_t client_addrlen = sizeof (client_address);
                int connfd = accept (listenfd, (struct sockaddr*) &client_address,
                                     &client_addrlen);
                if (connfd < 0) {
                    printf ("errno is: %d\n", errno);
                    continue;
                }
                if (user_count >= USER_LIMIT) {
                    const char* info = "Too many users...";
                    printf ("%s\n", info);
                    send (connfd, info, strlen (info), 0);
                    close (connfd);
                    continue;
                }
                // 儲存第user_count個客戶連接配接的相關資料
                users[user_count].address = client_address;
                users[user_count].connfd = connfd;
                // 父子程序建立管道,傳遞必要的資料
                ret = socketpair (PF_UNIX, SOCK_STREAM, 0, users[user_count].pipefd);
                if (ret < 0) {
                    perror ("socketpair() error\n");
                    close (connfd);
                    continue;
                }

                pid_t pid = fork();
                if (pid < 0) {
                    close (connfd);
                    continue;
                } else if (pid == 0) {
                    close (epollfd);
                    close (listenfd);
                    close (users[user_count].pipefd[0]);
                    close (sig_pipefd[0]);
                    close (sig_pipefd[1]);
                    run_child (user_count, users, share_mem);
                    munmap ( (void*) share_mem, USER_LIMIT * BUFFER_SIZE);
                    exit (0);
                } else {
                    close (connfd);
                    close (users[user_count].pipefd[1]);
                    addfd (epollfd, users[user_count].pipefd[0]);
                    users[user_count].pid = pid;
                    // 記錄新的客戶連接配接在數組users中的索引值,
                    // 建立程序pid和該索引值之間的映射關系
                    sub_process[pid] = user_count;
                    ++user_count;
                }
            } else if (sockfd == sig_pipefd[0] && event & EPOLLIN) {
                // 處理信号事件
                char signals[1024];
                memset (signals, 0, sizeof (signals) );
                ret = recv (sig_pipefd[0], signals, sizeof (signals), 0);
                if (ret <= 0) {
                    continue;
                } else {
                    for (int i = 0; i < ret; ++i) {
                        switch (signals[i]) {
                        case SIGCHLD:  // 子程序退出,有用戶端斷開連接配接
                            pid_t pid;
                            int stat;
                            while ( (pid = waitpid (-1, &stat, WNOHANG) ) > 0) {
                                int del_user = sub_process[pid];
                                sub_process[pid] = -1;
                                if (del_user < 0 || del_user > USER_LIMIT) {
                                    continue;
                                }
                                // 清除請求的相關資料
                                epoll_ctl (epollfd, EPOLL_CTL_DEL, \
                                           users[del_user].pipefd[0], 0);
                                close (users[del_user].pipefd[0]);
                                users[del_user] = users[--user_count];
                                sub_process (users[del_user].pid) = del_user;
                            }

                            if (terminate && user_count == 0) {
                                stop_server = true;
                            }
                            break;
                        }
                    case SIGTERM:
                    case SIGINT: {
                            // 結束伺服器程式
                            puts ("kill all child now");
                            if (user_count <= 0) {
                                stop_server = true;
                                break;
                            }

                            for (int i = 0; i < user_count; ++i) {
                                int pid = users[i].pid;
                                kill (pid, SIGTERM);
                            }
                            terminate = true;
                            break;
                        }
                    default:
                        break;
                    }
                }
            } else if (event & EPOLLIN) {  // 寫入資料
                int child = 0;
                ret = recv (sockfd, (char*) &child, sizeof (child), 0);
                if (ret <= 0 ) {
                    continue;
                } else {
                    for (int j = 0; j < user_count; ++j) {
                        if (users[j].pipefd[0] != sockfd) {
                            printf ("send data to child accross pipe\n");
                            send (users[j].pipefd[0], (char*) &child, sizeof (child), 0);
                        }
                    }
                }
            }
        }
    }

    del_resource();
    return 0;
}
           

繼續閱讀