structmsqid_ds { structipc_permmsg_perm;/* see Section 15.6.2 */ msgqnum_t msg_qnum; /* # of messages on queue */ msglen_t msg_qbytes; /* max # of bytes on queue */ pid_t msg_lspid; /* pid of last msgsnd() */ pid_t msg_lrpid; /* pid of last msgrcv() */ time_t msg_stime; /* last-msgsnd() time */ time_t msg_rtime; /* last-msgrcv() time */ time_t msg_ctime; /* last-change time */ //... };
intmsgget(key_t key, int flag); intmsgctl(int msqid, int cmd, struct msqid_ds *buf); intmsgsnd(int msqid, constvoid *ptr, size_t nbytes, int flag); ssize_tmsgrcv(int msqid, void *ptr, size_t nbytes, long type, int flag);
信号量
信号量是一个计数器,用于为多个进程提供对共享数据对象的访问。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<sys/sem.h> intsemget(key_t key, int nsems, int flag); intsemctl(int semid, int semnum, int cmd, .../* union semun arg */);
unionsemun{ int val; structsemid_ds *buf; unsignedshort *array; };
chararray[ARRAY_SIZE]; /* uninitialized data = bss */
intmain(void) { int shmid; char *ptr, *shmptr;
printf("array[] from %lx to %lx\n", (unsignedlong)&array[0], (unsignedlong)&array[ARRAY_SIZE]); printf("stack around %lx\n", (unsignedlong)&shmid);
if ((ptr = malloc(MALLOC_SIZE)) == NULL) err_sys("malloc error"); printf("malloced from %lx to %lx\n", (unsignedlong)ptr, (unsignedlong)ptr+MALLOC_SIZE);
if ((shmid = shmget(IPC_PRIVATE, SHM_SIZE, SHM_MODE)) < 0) err_sys("shmget error"); if ((shmptr = shmat(shmid, 0, 0)) == (void *)-1) err_sys("shmat error"); printf("shared memory attached from %lx to %lx\n", (unsignedlong)shmptr, (unsignedlong)shmptr+SHM_SIZE);
if (shmctl(shmid, IPC_RMID, 0) < 0) err_sys("shmctl error");
exit(0); }
POSIX信号量
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include<semaphore.h> sem_t *sem_open(constchar *name, int oflag, .../* mode_t mode, unsigned int value */); intsem_close(sem_t *sem); intsem_unlink(constchar *name); intsem_trywait(sem_t *sem); intsem_wait(sem_t *sem); #include<time.h> intsem_timedwait(sem_t *restrict sem, conststruct timespec *restrict tsptr); intsem_post(sem_t *sem); intsem_init(sem_t *sem, int pshared, unsignedint value); intsem_destroy(sem_t *sem); intsem_getvalue(sem_t *restrict sem, int *restrict valp);