进程间通信:管道,信号量,共享内存,消息队列

1.管道:

Int fd[2];

int pipe(fd);创建了一个管道,不过是单向的。fd[0]为读端,fd[1]为写端

int socketpair(int domain, int type, int protocol, int fd[2]);双向管道

2.信号量:

#include<sys/sem.h>

int  semget(key_t key,int num_sems,int sem_flags);

int semop(int sem_id,struct sembuf* sem_ops,size_t num_sem_ops);

semctl(int sem_id,int sem_num,int command,...);

下面是使用信号量的实例:

#include <sys/sem.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

union semun
{
     int val;                  
     struct semid_ds* buf;     
     unsigned short int* array;
     struct seminfo* __buf;    
};

void pv( int sem_id, int op )
{
    struct sembuf sem_b;
    sem_b.sem_num = 0;
    sem_b.sem_op = op;
    sem_b.sem_flg = SEM_UNDO;
    semop( sem_id, &sem_b, 1 );
}

int main( int argc, char* argv[] )
{
    int sem_id = semget( IPC_PRIVATE, 1, 0666 );

    union semun sem_un;
    sem_un.val = 1;
    semctl( sem_id, 0, SETVAL, sem_un );

    pid_t id = fork();
    if( id < 0 )
    {
        return 1;
    }
    else if( id == 0 )
    {
        printf( "child try to get binary sem\n" );
        pv( sem_id, -1 );
        printf( "child get the sem and would release it after 5 seconds\n" );
        sleep( 5 );
        pv( sem_id, 1 );
        exit( 0 );
    }
    else
    {
        printf( "parent try to get binary sem\n" );
        pv( sem_id, -1 );
        printf( "parent get the sem and would release it after 5 seconds\n" );
        sleep( 5 );
        pv( sem_id, 1 );
    }

    waitpid( id, NULL, 0 );
    semctl( sem_id, 0, IPC_RMID, sem_un );
    return 0;
}
3.共享内存:

#include<sys/shm.h>

int shmget(key_t key,size_t size,int shmflg);

void* shmat(int shm_id,const void* shm_addr,int shmflg);

int shmdt(const  void* shm_addr);

int shmctl(int shm_id,int command,struct shmid_ds* buf);

4.消息队列:

#include<sys/msg.h>

int msgget(key_t key,int msgflg);

int msgsnd(int msgid,const void* msg_ptr,size_t msg_sz,int msgflg);

int msgrcv(int msgid,void* msg_ptr,size_t msg_sz,long int msgtype,int msgflg);

int msgctl(int msgid,int command,struct msgid_ds* buf);



你可能感兴趣的:(linux)