關於部落格
  • 26394

    累積人氣

  • 0

    今日人氣

    0

    訂閱人氣

//接收端

//接收端 #if defined(__GNU_LIBRARY__) && !defined(_SEM_SEMUN_UNDEFINED) /* union semun is defined by including */ #else /* according to X/OPEN we have to define it ourselves */ union semun { int val; /* value for SETVAL */ struct semid_ds *buf; /* buffer for IPC_STAT, IPC_SET */ unsigned short int *array; /* array for GETALL, SETALL */ struct seminfo *__buf; /* buffer for IPC_INFO */ }; #endif #include #include #include #include #include #include #include #define MAX_TEXT 512 static int semaphore_pend(void); static int semaphore_post(void); static int set_semvalue(void); static void del_semvalue(void); static int sem_id; struct my_msg_st { long int my_msg_type; char some_text[MAX_TEXT]; }; int main(int argc, char *argv[]) { int i; int pause_time; i=1; int msgid; struct my_msg_st some_data; long int msg_to_receive = 0; srand((unsigned int)getpid()); sem_id = semget((key_t)1234, 1, 0666 | IPC_CREAT); msgid = msgget((key_t)1111, 0666 | IPC_CREAT); set_semvalue(); //初始號誌的初值 printf("nReceiver check semphore per 1 sec n"); while(i<20){ sleep(1); if (!semaphore_pend()) exit(EXIT_FAILURE); msgrcv(msgid, (void *)&some_data, BUFSIZ,msg_to_receive, 0); printf("Receiver got %d th semphore n", i); printf("Receiver got: %s", some_data.some_text); if (strncmp(some_data.some_text, "end", 3) == 0) i = 20; i++; } pause_time = rand() % 3; msgctl(msgid, IPC_RMID, 0); del_semvalue(); //刪除號誌 exit(EXIT_SUCCESS); } /* The function set_semvalue initializes the semaphore using the SETVAL command in a semctl call. We need to do this before we can use the semaphore. */ static int set_semvalue(void) { union semun sem_union; sem_union.val = 0; if (semctl(sem_id, 0, SETVAL, sem_union) == -1) return(0); return(1); } /* The del_semvalue function has almost the same form, except the call to semctl uses the command IPC_RMID to remove the semaphore's ID. */ static void del_semvalue(void) { union semun sem_union; if (semctl(sem_id, 0, IPC_RMID, sem_union) == -1) fprintf(stderr, "Failed to delete semaphoren"); } /* semaphore_pend changes the semaphore by -1 (waiting). */ static int semaphore_pend(void) { struct sembuf sem_b; sem_b.sem_num = 0; sem_b.sem_op = -1; /* P() */ sem_b.sem_flg = SEM_UNDO; if (semop(sem_id, &sem_b, 1) == -1) { fprintf(stderr, "semaphore_pend failedn"); return(0); } return(1); } /* semaphore_post is similar except for setting the sem_op part of the sembuf structure to 1, so that the semaphore becomes available. */ static int semaphore_post(void) { struct sembuf sem_b; sem_b.sem_num = 0; sem_b.sem_op = 1; /* V() */ sem_b.sem_flg = SEM_UNDO; if (semop(sem_id, &sem_b, 1) == -1) { fprintf(stderr, "semaphore_post failedn"); return(0); } return(1); }
相簿設定
標籤設定
相簿狀態