int main(int argc,char *argv) { pid_t pid; int i; int value; key_t key; int status; if((pid=fork())==-1) { perror("fork"); exit(EXIT_FAILURE); } else if(pid==0) { if((sem_id=semget((key_t)123456,1,IPC_CREAT|0770))==-1) { perror("semget"); exit(EXIT_FAILURE); } if (!set_semvalue()) { fprintf(stderr, "Failed to initialize semaphore\n"); exit(EXIT_FAILURE); } value=get_semvalue(); printf("this is child,the current value is %d\n",value); if(!semaphore_v()) { fprintf(stderr, "Failed to v operator\n"); exit(EXIT_FAILURE); } value=get_semvalue(); printf("the child %d V operator,value=%d\n",i,value); printf("child exit success\n"); exit(EXIT_SUCCESS); } else //parent { sleep(3); if((sem_id=semget((key_t)123456,1,IPC_CREAT|0770))==-1) { perror("semget"); exit(EXIT_FAILURE); } value=get_semvalue(); printf("this is parent ,the current value is %d\n",value); printf("the parent will remove the sem\n"); if(semctl(sem_id,0, IPC_RMID,(struct msquid_ds*)0)==-1) { perror("semctl"); exit(EXIT_FAILURE); } return 0; } }
int main(int argc,char **argv) { int i ; int pause_time; char op_char = 'O'; srand((unsigned int)getpid()); //create semaphore sem_id = semget((key_t)1234,1,0666|IPC_CREAT); if (argc >1) { //set sempvalue 初始化信号量 if (!set_semvalue()) { fprintf(stderr,"Failed to initialize semaphore"); exit(EXIT_FAILURE); } op_char = 'X'; sleep(2); } for (i = 0; i < 10; ++i) { //设置信号量 等待进入 if (!semaphore_p()) { exit(EXIT_FAILURE); } printf("%c",op_char); fflush(stdout); pause_time = rand() % 3; sleep(pause_time); printf("%c",op_char); fflush(stdout); //退出临界区,信号量设置为可用 if (!semaphore_v()) { exit(EXIT_FAILURE); } pause_time = rand() % 3; sleep(pause_time); } printf("\n%d - finished \n",getpid()); if (argc>1) { sleep(10); //删除信号量 del_semvalue(); } exit(EXIT_SUCCESS); }
int main(int argc, char* argv[]) { int i; int pause_time; char op_char = 'O'; srand((unsigned int)getpid()); sem_id = semget((key_t)1234, 1, 0666 | IPC_CREAT); if (argc > 1) { if (!set_semvalue()) { fprintf(stderr, "Failed to initialize semaphore\n"); exit(EXIT_FAILURE); } op_char = 'X'; sleep(2); } /* Then we have a loop which enters and leaves the critical section ten times. There, we first make a call to semaphore_p which sets the semaphore to wait, as this program is about to enter the critical section. */ for (i = 0; i < 10; i++) { if (!semaphore_p()) { exit(EXIT_FAILURE); } printf("%c", op_char); fflush(stdout); pause_time = rand() % 3; sleep(pause_time); printf("%c", op_char); fflush(stdout); /* After the critical section, we call semaphore_v, setting the semaphore available, before going through the for loop again after a random wait. After the loop, the call to del_semvalue is made to clean up the code. */ if (!semaphore_v()) { exit(EXIT_FAILURE); } pause_time = rand() % 2; sleep(pause_time); } printf("\n%d - finished\n", getpid()); if (argc > 1) { sleep(10); del_semvalue(); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { char message = 'X'; int i = 0; /* 创建信号量 */ sem_id = semget((key_t)1234, 1, 0666 | IPC_CREAT); if(argc > 1) { /* 程序第一次被调用,初始化信号量 */ if(!set_semvalue()) { fprintf(stderr, "Failed to initialize semaphore\n"); exit(EXIT_FAILURE); } /* 设置要输出到屏幕中的信息,即其参数的第一个字符 */ message = argv[1][0]; sleep(2); } for(i = 0; i < 10; ++i) { /* 进入临界区 */ if(!semaphore_p()) { exit(EXIT_FAILURE); } /* 向屏幕中输出数据 */ printf("%c", message); /* 清理缓冲区,然后休眠随机时间 */ fflush(stdout); sleep(rand() % 3); /* 离开临界区前再一次向屏幕输出数据 */ printf("%c", message); fflush(stdout); /* 离开临界区,休眠随机时间后继续循环 */ if(!semaphore_v()) { exit(EXIT_FAILURE); } sleep(rand() % 2); } sleep(10); printf("\n%d - finished\n", getpid()); if(argc > 1) { /* 如果程序是第一次被调用,则在退出前删除信号量 */ sleep(3); del_semvalue(); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { char message = 'X'; int i = 0; key_t key; key = ftok("/var/httcsec",IPC_ID); //创建信号量 printf("key:%d\n", (int)key); sem_id = semget(key, 1, 0666 | IPC_CREAT); if(argc > 1) { //程序第一次被调用,初始化信号量 if(!set_semvalue()) { fprintf(stderr, "Failed to initialize semaphore\n"); exit(EXIT_FAILURE); } //设置要输出到屏幕中的信息,即其参数的第一个字符 message = argv[1][0]; sleep(2); } for(i = 0; i < 3; ++i) { //进入临界区 if(!semaphore_p()) exit(EXIT_FAILURE); //向屏幕中输出数据 printf("..[%d]..lock\n", getpid()); //清理缓冲区,然后休眠随机时间 fflush(stdout); sleep(rand() % 5); //离开临界区前再一次向屏幕输出数据 printf("..[%d]..unlock\n", getpid()); fflush(stdout); //离开临界区,休眠随机时间后继续循环 if(!semaphore_v()) exit(EXIT_FAILURE); printf("..[%d]..waiting\n", getpid()); fflush(stdout); } printf("\n%d - finished\n", getpid()); if(argc > 1) { //如果程序是第一次被调用,则在退出前删除信号量 sleep(3); del_semvalue(); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int i; srand((unsigned int)getpid()); sem_id = semget((key_t)4321, 1, 0666); printf("sem_id_%s = %d\n",argv[1], sem_id); if(sem_id < 0) { sem_id = semget((key_t)4321, 1, 0666|IPC_CREAT); printf("sem_id_2_%s = %d\n", argv[1] , sem_id); } if(argc > 1) { if(!set_semvalue()) { fprintf(stderr, "Failed to initlize semaphore\n"); exit(EXIT_FAILURE); } op_char = argv[1]; // sleep(2); } for(i = 0; i< 10; i++) { /****************** P *********************/ if(!semaphore_p()) exit(EXIT_FAILURE); do_my_job(); //do something /****************** V *********************/ if(!semaphore_v()) exit(EXIT_FAILURE); pause_time = rand()%2; // sleep(pause_time); }//for printf("\n%d - finished \n", getpid()); if(argc > 1) { // sleep(10); del_semvalue(); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int i; int pause_time; char op_char='O'; srand((unsigned int)getpid()); sem_id = semget((key_t)4321, 1, 0666|IPC_CREAT); if(argc > 1) { if(!set_semvalue()) { fprintf(stderr, "Failed to initlize semaphore\n"); exit(EXIT_FAILURE); } op_char = 'X'; sleep(2); } for(i = 0; i< 10; i++) { if(!semaphore_p()) exit(EXIT_FAILURE); printf("%c is doing job\n", op_char); fflush(stdout); pause_time = rand()%3; sleep(pause_time); printf("%c is done\n", op_char); fflush(stdout); if(!semaphore_v()) exit(EXIT_FAILURE); pause_time = rand()%2; sleep(pause_time); }//for printf("\n%d - finished \n", getpid()); if(argc > 1) { sleep(10); del_semvalue(); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int i; int pause_time; char op_char = 'O'; // initialize the random seed srand( (unsigned int) getpid() ); // creates a new semaphore (only 1) with modes + create if doesn't ex sem_id = semget( (key_t)1234, 1, 0666 | IPC_CREAT); // if invoked with parameters (must be the first invocation) if ( argc > 1 ) { if ( ! set_semvalue() ) { fprintf (stderr, "failed to init semaphore\n"); exit (EXIT_FAILURE); } op_char = 'X'; // gives time to start the second semaphore sleep (2); } // normal run for ( i = 0 ; i < 10 ; i++ ) { if ( !semaphore_p() ) exit (EXIT_FAILURE); printf ("%c", op_char); fflush (stdout); pause_time = rand() % 3; sleep (pause_time); printf("%c", op_char); fflush (stdout); if ( ! semaphore_v() ) exit (EXIT_FAILURE); pause_time = rand() % 2; sleep (pause_time); } printf ("\n%d - finished\n", getpid() ); if (argc > 1 ) { sleep (10); del_semvalue(); } exit (EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int i; int pause_time; char op_char = 'O'; srand((unsigned int)getpid()); sem_id = semget((key_t)1234, 1, 0666 | IPC_CREAT); // if there's an arg, set op_char to X and create the semaphore if (argc > 1) { if (!set_semvalue()) { fprintf(stderr, "Failed to initialize semaphore\n"); exit(EXIT_FAILURE); } op_char = 'X'; sleep(2); } // take turns locking, printing to stdout and flushing, // and then unlocking and waiting. for(i = 0; i < 10; i++) { // lock around the printing and a short pause if (!semaphore_p()) exit(EXIT_FAILURE); printf("%c", op_char);fflush(stdout); pause_time = rand() % 3; sleep(pause_time); printf("%c", op_char);fflush(stdout); if (!semaphore_v()) exit(EXIT_FAILURE); // then do a random pause while unlocked pause_time = rand() % 2; sleep(pause_time); } printf("\n%d - finished\n", getpid()); // it's very important to delete the semaphore you created! if (argc > 1) { sleep(10); del_semvalue(); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int sem_id; char ch = 'O'; int i, pause_time; srand((unsigned int)getpid()); sem_id = semget((key_t)1234, 1, 0666|IPC_CREAT); if(sem_id < 0) { fprintf(stderr, "get semaphore id failed\n"); exit(1); } if(argc > 1) { if(!set_semvalue(sem_id)) { fprintf(stderr, "initialize semaphore failed\n"); exit(1); } ch = 'X'; sleep(2); } for(i = 0; i < 10; ++i) { if(!semaphore_p(sem_id)) exit(1); printf("%c", ch); fflush(stdout); pause_time = rand() % 3; sleep(pause_time); printf("%c", ch); fflush(stdout); if(!semaphore_v(sem_id)) exit(1); } if(argc > 1) { sleep(10); del_semvalue(sem_id); } exit(0); }
int main(int argc, char *argv[]) { pid_t pid; int value; key_t key; if((pid=fork()) == -1){ perror("fork"); exit(EXIT_FAILURE); }else if (pid == 0){ if((sem_id=semget((key_t)123456, 1, 0770|IPC_CREAT)) == -1){ perror("semget"); exit(EXIT_FAILURE); } if(!set_semvalue()){ printf("failed initialized semaphore\n"); exit(EXIT_FAILURE); } value = get_semvalue(); printf("child: the current value is %d\n",value); if(!semaphore_v()){ printf("failed to v operator\n"); exit(EXIT_FAILURE); } value = get_semvalue(); printf("child: v operator, value=%d\n", value); printf("child: exit success\n"); exit(EXIT_SUCCESS); }else{ sleep(3); if((sem_id = semget((key_t)123456, 1, 0770|IPC_CREAT)) == -1){ perror("semget"); exit(EXIT_FAILURE); } value=get_semvalue(); printf("parent: the current value is %d\n", value); printf("parent: will remove the sem\n"); if(semctl(sem_id, 0, IPC_RMID, (struct msquid_ds *)0) == -1){ perror("semclt"); exit(EXIT_FAILURE); } } return 0; }
int main(int argc, char *argv[]) { int i; int pause_time; char op_char = '0'; srand((unsigned int)getpid()); // 创建信号量 sem_id = semget((key_t)1234, 1, 0666 | IPC_CREAT); if (argc > 1) { // 当参数大于1个时候, 初始化信号量, 让op_char 为 'X' if (!set_semvalue()) { fprintf(stderr, "Failed to initialize semaphore\n"); exit(EXIT_SUCCESS); } op_char = 'X'; sleep(2); } for (i = 0; i < 10; i++) { // 执行p操作, 减1 if (!sem_operation_p()) exit(EXIT_SUCCESS); printf("%c", op_char);fflush(stdout); // 休息(随机数,(0, 3])s pause_time = rand() % 3; sleep(pause_time); printf("%c", op_char);fflush(stdout); // 执行v操作, 加1 if (!sem_operation_v()) exit(EXIT_SUCCESS); // 休息(随机数,(0, 2])s pause_time = rand() % 2; sleep(pause_time); } printf("\n%d - finished\n", getpid()); if (argc > 1) { sleep(10); del_semvalue(); } exit(EXIT_SUCCESS); }
int main(int argc,char *argv[]){ int i; int pause_time; char op_char='O'; srand((unsigned int)getpid()); sem_id = semget((key_t)1234,1,0666|IPC_CREAT);// 產生一個新號誌 或者根據key 取得一個已存在的號誌 666為設定權限 if(argc >1){ // 假設第一次執行時 使用參數 if(!set_semvalue()){ // setctl回傳-1時(發生錯誤) fprintf(stderr,"Failed to initialize semaphore\n"); exit(EXIT_FAILURE); } op_char='X'; sleep(2); } /* 然後進入迴圈 進出入 "critical section" 十次 * 在那裡 首先先呼叫semaphore_p 讓即將進入critical section 的semaphore等待*/ for(i=0;i<10;i++){ if(!semaphore_p()) exit(EXIT_FAILURE); printf("%c",op_char);fflush(stdout); pause_time=rand()%3; sleep(pause_time); printf("%c",op_char);fflush(stdout); /* 在critical section 之後 呼叫semaphore_v * 再進去for loop 之前 等待一段亂數時間 然後del sem 結束*/ if(!semaphore_v()) exit(EXIT_FAILURE); pause_time=rand()%2; sleep(pause_time); } printf("\n%d - finished\n",getpid()); if(argc>1){ sleep(10); del_semvalue(); } exit(EXIT_SUCCESS); }
int main() { int i; int prio_inheritance=0; /************************************ Process 2 (Low Priority) **********************************/ int PID_L = getpid(); int PR_L = getpriority(PRIO_PROCESS,PID_L); printf("The Priority of LOW Process %d = %d\n", PID_L,PR_L); key_t key; int shm_id; char *shm, *s; char c; key = 5788; // name the shared memory shm_id= shmget(key,100, IPC_EXCL | 0666); // make a shared memory of 27 bytes if(shm_id < 0) { perror("shmget"); exit(1); } // Now attach the shared memory to our data space if((shm = shmat(shm_id,NULL,0)) == (char *) -1) { perror("shmat"); exit(1); } sem_id = semget(key,1,0666 | IPC_CREAT); if(!set_semvalue()) { fprintf(stderr,"Failed to initiaalize the semaphore \n"); exit(EXIT_FAILURE); } /* FILE *f = fopen("shared_mem_info.txt","r"); if (f == NULL) { printf("Error in opening file!!! \n"); exit(1); } fscanf(f,"%d",&shm_id); fclose(f); printf("shared memory id = %d \n",shm_id); */ printf("Address = %d\n",shm); for(s=shm; *s !=NULL; s++) { putchar(*s); } putchar('\n'); union semun sem_union; who_locked = semctl(sem_id,0,GETPID,sem_union); if(who_locked > 0) { printf("The PID = %d has locked the Semaphore. . . \n",who_locked); /* setpriority(PRIO_PROCESS,who_locked,PRIO_H); prio_inheritance = 1; printf("The PID = %d has inherited priority of High that is %d...\n",who_locked,PRIO_H); sched_yield();*/ } sem_lock(); printf("High process has acquired the lock\n"); *shm='*'; /*Low Priority Task tries to acquire to lock the semaphore*/ /* sem_lock(); printf("Low Priority Process locks semaphore\n"); for(i=0;i<50;i++) printf("Low Prio task is running...\n"); sem_unlock(); printf("Low Priority task is completed...\n"); printf("Inheritance = %d \n",prio_inheritance); prio_inheritance = 0; printf("Inheritance = %d \n",prio_inheritance); */ return 0; }
int main() { //counters and size variables int nread; int n = 0; //buffer to read in from the file char buffer[BUFSIZ]; //declaring shared memory space and message void *shared_memory = (void *)0; struct buffer_msg *msg; int id; //declaring the necessary semaphore ids int sem_id_s; int sem_id_n; int sem_id_e; //creating the semaphores and setting their values sem_id_n = semget((key_t)key_n, 1, 0666 | IPC_CREAT); sem_id_s = semget((key_t)key_s, 1, 0666 | IPC_CREAT); sem_id_e = semget((key_t)key_e, 1, 0666 | IPC_CREAT); if (!set_semvalue(1, sem_id_s)) { fprintf(stderr, "Failed to initialize semaphore\n"); exit(EXIT_FAILURE); } if (!set_semvalue(0, sem_id_n)) { fprintf(stderr, "Failed to initialize semaphore\n"); exit(EXIT_FAILURE); } if (!set_semvalue(NBUFFER, sem_id_e)) { fprintf(stderr, "Failed to initialize semaphore\n"); exit(EXIT_FAILURE); } //creating and attaching the shared memory with its address space id = shmget((key_t)key, MEMSIZE, 0666|IPC_CREAT); if(id==-1) { fprintf(stderr, "shmget failed\n"); exit(EXIT_FAILURE); } shared_memory = shmat(id, (void *)0, 0); if(shared_memory == (void *)-1) { fprintf(stderr, "shmat failed\n"); exit(EXIT_FAILURE); } //reading in the message from the file nread = read(0, buffer, BUFSIZ); //BUFSIZ is from stdio.h if(nread==-1) { fprintf(stderr, "nread failed\n"); exit(EXIT_FAILURE); } //iterate through the read in message int i = 0; int count = 0; msg = (struct buffer_msg *)shared_memory; while(n<nread) { //wait to be able to add something into the shared memory buffer (so it does not overflow) and ensure mutual exclusion is held semaphore_p(sem_id_e); semaphore_p(sem_id_s); //these can be commented out to achieve the same result if there is only one producer and one consumer //copy what is in the read in buffer to shared memory strncpy(msg->buffer[i].msg, buffer+n, TEXTSIZE); //put the size of the message in shared memory msg->buffer[i].size = strlen(msg->buffer[i].msg); count+=msg->buffer[i].size; //signal that something is in the shared memory buffer and that it has left the critical section semaphore_v(sem_id_s); //these can be commented out to achieve the same result if there is only one producer and one consumer semaphore_v(sem_id_n); i = (i + 1) % NBUFFER; n += TEXTSIZE; } printf("Read in %i bytes\n", count); }
int main(int argc, char *argv[]) { int i; char op_char = 'O'; int pause_time; srand(getpid()); sem_id = semget((key_t)123, 1, 0666 | IPC_CREAT); if (-1 == sem_id) { perror("Failed to create semaphore. "); printf("Error: %s\n", strerror(errno)); exit(1); } if (argc > 1) { if (!set_semvalue()) { fprintf(stderr, "Failed to initialize semaphore.\n"); exit(EXIT_FAILURE); } op_char = 'X'; sleep(2); } for (i = 0; i < 10; ++i) { if (!sem_p()) { exit(EXIT_FAILURE); } printf("%c", op_char); fflush(stdout); pause_time = rand() % 3; sleep(pause_time); printf("%c", op_char); fflush(stdout); if (!sem_v()) { exit(EXIT_FAILURE); } pause_time = rand() % 2; sleep(pause_time); } printf("\n%d - finished\n", getpid()); if (argc > 1) { sleep(10); del_semvalue(); } exit(EXIT_SUCCESS); }
/************************************************************ * function: create or open the shared memory. * iscreated: 1, to create the shm; 0, only to open the shm. * mqsize: the count of the items * itemsize: the size of an item (bytes) * return: 0, correct; others, error number. ***********************************************************/ int shmmq_open(int iscreated, int mqsize, int itemsize) { int nflag; int ret = 0; /* Initial semaphore */ g_s_semid = get_semvalue((key_t)SEM_KEY); if (-1 == g_s_semid) { return ERROR_GET_SEMVALUE; } if (iscreated && -1 == set_semvalue(g_s_semid)) { return ERROR_SET_SEMVALUE; } if (-1 == semaphore_p(g_s_semid)) { return ERROR_SEMAPHORE_P; } while (1) { if (iscreated) { nflag = 0666 | IPC_CREAT; } else { nflag = 0666; } g_s_mqsize = (mqsize <= 0) ? DEFAULT_MQ_SIZE : mqsize; g_s_itemsize = (itemsize <= 0) ? DEFAULT_ITEM_SIZE : itemsize; /* Initial shared memory */ g_s_shmid = shmget((key_t)SHM_KEY, g_s_mqsize * g_s_itemsize + DEFAULT_HEAD_SIZE, nflag); if (-1 == g_s_shmid) { ret = ERROR_SHMGET; break; } g_s_pbase = shmat(g_s_shmid, NULL, 0); if ((void *)-1 == g_s_pbase) { g_s_pbase = NULL; ret = ERROR_SHMAT; break; } g_s_phead = (shmmq_head*)g_s_pbase; g_s_pcontent = g_s_pbase + DEFAULT_HEAD_SIZE; /* Initial head of the shared memory */ if (iscreated) { g_s_phead->enq_pos = -1; g_s_phead->deq_pos = -1; } break; } if (ret && iscreated) { if (g_s_shmid >= 0) shmctl(g_s_shmid, IPC_RMID, 0); semaphore_v(g_s_semid); del_semvalue(g_s_semid); return ret; } if (-1 == semaphore_v(g_s_semid)) { return ERROR_SEMAPHORE_V; } return ret; }
int main() { int sem_S, sem_N, sem_E; int number; int shmid; int position = 0; int running = 1; void *shared_memory = (void *)0; struct shared_use_st *shared_stuff; srand((unsigned int)getpid()); shmid = shmget((key_t)1000, sizeof(struct shared_use_st), 0666 | IPC_CREAT); if (shmid == -1) { fprintf(stderr, "shmget failed\n"); exit(EXIT_FAILURE); } sem_S = semget((key_t)1111, 1, 0666 | IPC_CREAT); set_semvalue(sem_S, 1); printf("Sem S: %i\n",sem_S); sem_N = semget((key_t)2222, 1, 0666 | IPC_CREAT); set_semvalue(sem_N, 0); printf("Sem N: %i\n",sem_N); sem_E = semget((key_t)3333, 1, 0666 | IPC_CREAT); set_semvalue(sem_E, TEXT_SZ); printf("Sem E: %i\n",sem_E); shared_memory = shmat(shmid, (void *)0, 0); if (shared_memory == (void *)-1) { fprintf(stderr, "shmat failed\n"); exit(EXIT_FAILURE); } printf("Memory attached at %X\n", (int)shared_memory); shared_stuff = (struct shared_use_st *)shared_memory; shared_stuff->in = 0; shared_stuff->out = 0; while(running) { number = (rand()%40); wait(sem_E); wait(sem_S); shared_stuff->some_number[shared_stuff->in] = number; printf("pid %d puts number %d at position %d\n",getpid(),number,shared_stuff->in); if(shared_stuff->in == TEXT_SZ) { shared_stuff->in = 0; }else{ shared_stuff->in = (shared_stuff->in+1)%TEXT_SZ; } signal(sem_S); signal(sem_N); if(number == -1) { running = 0; } sleep(4); } if (shmdt(shared_memory) == -1) { fprintf(stderr, "shmdt failed\n"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
int main() { int sem_S, sem_N, sem_E; int number; int shmid; int position = 0; int running = 1; void *shared_memory = (void *)0; struct shared_use_st *shared_stuff; shmid = shmget((key_t)1000, sizeof(struct shared_use_st), 0666 | IPC_CREAT); if (shmid == -1) { fprintf(stderr, "shmget failed\n"); exit(EXIT_FAILURE); } sem_S = semget((key_t)1111, 1, 0666 | IPC_CREAT); set_semvalue(sem_S, 1); printf("Sem S: %i\n",sem_S); sem_N = semget((key_t)2222, 1, 0666 | IPC_CREAT); set_semvalue(sem_N, 0); printf("Sem N: %i\n",sem_N); sem_E = semget((key_t)3333, 1, 0666 | IPC_CREAT); set_semvalue(sem_E, TEXT_SZ); printf("Sem E: %i\n",sem_E); /* We now make the shared memory accessible to the program. */ shared_memory = shmat(shmid, (void *)0, 0); if (shared_memory == (void *)-1) { fprintf(stderr, "shmat failed\n"); exit(EXIT_FAILURE); } printf("Memory attached at %X\n", (int)shared_memory); /* The next portion of the program assigns the shared_memory segment to shared_stuff, which then prints out any text in written_by_you. The loop continues until end is found in written_by_you. The call to sleep forces the consumer to sit in its critical section, which makes the producer wait. */ shared_stuff = (struct shared_use_st *)shared_memory; while(running) { wait(sem_N); wait(sem_S); number = shared_stuff->some_number[shared_stuff->out]; printf("pid %d takes number %d at position %d\n",getpid(),number,shared_stuff->out); if(shared_stuff->out == TEXT_SZ) { shared_stuff->out = 0; }else{ shared_stuff->out = (shared_stuff->out+1)%TEXT_SZ; } signal(sem_S); signal(sem_E); if(number == -1) { running = 0; } if(position == TEXT_SZ) { position = 0; } sleep(1); } /* if (shared_stuff->written_by_you) { printf("You wrote: %d\n", shared_stuff->some_number); sleep( rand() % 4 ); // make the other process wait for us ! shared_stuff->written_by_you = 0; if (shared_stuff->some_number == -1) { running = 0; } } }*/ /* Lastly, the shared memory is detached and then deleted. */ if (shmdt(shared_memory) == -1) { fprintf(stderr, "shmdt failed\n"); exit(EXIT_FAILURE); } if (shmctl(shmid, IPC_RMID, 0) == -1) { fprintf(stderr, "shmctl(IPC_RMID) failed\n"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
int main() { int i; int prio_inheritance=0; /* int shm_id=0; char *shm, *s; FILE *f = fopen("shared_mem_info.txt","r"); if (f == NULL) { printf("Error in opening file!!! \n"); exit(1); } fscanf(f,"%d",&shm_id); fclose(f); printf("shared memory id = %d \n",shm_id); } */ /************************************* Process 1 (High Priority) *********************************/ key_t key; int shm_id; char *shm, *s; char c; key = 5788; // name the shared memory shm_id= shmget(key,100, IPC_CREAT | 0666); // make a shared memory of 27 bytes if(shm_id < 0) { perror("shmget"); exit(1); } // Now attach the shared memory to our data space if((shm = shmat(shm_id,NULL,0)) == (char *) -1) { perror("shmat"); exit(1); } s = shm; // Now we will write in the memory FILE *f = fopen("shared_mem_info.txt","w"); if (f == NULL) { printf("Error in opening file!!! \n"); exit(1); } fprintf(f,"%d\n",shm_id); fclose(f); sem_id = semget(key,1,0666 | IPC_CREAT); if(!set_semvalue()) { fprintf(stderr,"Failed to initiaalize the semaphore \n"); exit(EXIT_FAILURE); } // It is the parent process. I have schedule it as high priority process. int PID_H = getpid(); int PR_H = getpriority(PRIO_PROCESS,PID_H); printf("The Priority of High Process %d = %d\n", PID_H,PR_H); setpriority(PRIO_PROCESS,PID_H,PRIO_H); printf("The Priority of High Process %d changes = %d\n", PID_H,PRIO_H); usleep(200); printf("High Prio task is now try to access the semaphore...\n"); union semun sem_union; who_locked = semctl(sem_id,0,GETPID,sem_union); // if(who_locked != PID_H) // { if(who_locked > 0) { printf("The PID = %d has locked the Semaphore. . . \n",who_locked); /*setpriority(PRIO_PROCESS,who_locked,PRIO_H); prio_inheritance = 1; printf("The PID = %d has inherited priority of High that is %d...\n",who_locked,PRIO_H); sched_yield();*/ } // } sem_lock(); printf("High process has acquired the lock\n"); printf("Address = %d\n",shm); for(c='a'; c<='z'; c++) { *s++ = c; } *s=NULL; printf("write succesfull...\n"); while(*shm != '*') { sleep(1); } for(i=0; i<40; i++) printf("High Prio task is running...\n"); sem_unlock(); printf("High process has unlock the semaphore... \n"); return 0; }
int main() { signal (SIGTERM, out); signal (SIGINT, out); int shmid; /* искать сегмент, соответствующий ключу key*/ shmid = shmget((key_t)1234, sizeof(struct memFormat), 0666); if (shmid == -1) {perror("shmget");return 0;} shared_memory = shmat(shmid, (void *)0, SHM_RDONLY); if (shared_memory == (void *)-1) {perror("shmat");return 0;} int sem_id = createSem(1,12345); if(sem_id==-1) {perror("createSem"); return 0;} if(set_semvalue(sem_id,0)==-1) {perror("set_semvalue"); return 0;} semaphore_p(sem_id); memcpy(&memf,shared_memory, sizeof(struct memFormat)); semaphore_v(sem_id); if (shmdt(shared_memory) == -1) {perror("shmat"); return 0;} int size = sizeof(struct memFormat)+(memf.max*memf.sizeItem); printf("Moniotr attache mem size: %d + %d=%d",sizeof(struct memFormat),(memf.max*memf.sizeItem),size); shmid = shmget((key_t)1234, size, 0666); if (shmid == -1) {perror("shmget2");return 0;} shared_memory = shmat(shmid, (void *)0, SHM_RDONLY); if (shared_memory == (void *)-1) {perror("shmat2");return 0;} pitem = (int*)shared_memory+sizeof(struct memFormat); printf("Monitor memory attached at %p,data attached at %p\n", shared_memory,pitem); printf("memory pid %d:\n sizeItem %d, count %d, max %d",memf.pidMaster,memf.sizeItem,memf.count,memf.max); sleep(1); while(bOut==false) { pitem = (int*)shared_memory+sizeof(struct memFormat); delay(500); int count1=0; if(!semaphore_p(sem_id)) {perror("semaphore_p");break;} memcpy(&memf,shared_memory, sizeof(struct memFormat)); for(int vi=0;vi<memf.count;vi++) { if(*pitem==1) count1++; //printf("%d.",*pitem); pitem++; } if(!semaphore_v(sem_id)) {perror("semaphore_v");break;} printf("\nnumber '1': %d.",count1); } if (shmdt(shared_memory) == -1) {perror("shmat2");} del_semvalue(sem_id,0); printf("\nExit...\n"); }
void main(int argc, char *argv[]) { int file_input; int shmid; int bytes_copied, buf_index = 0; char data[OUR_BUFSIZ]; char file_data[BUFSIZ]; void *shared_memory = (void *)0; // Set to null pointer (for now) circular_buf_st *shared_buffer; struct timeval start, end; /* Semaphores */ int sem_s_id = semget(S_KEY, 1, 0666 | IPC_CREAT); int sem_e_id = semget(E_KEY, 1, 0666 | IPC_CREAT); int sem_n_id = semget(N_KEY, 1, 0666 | IPC_CREAT); int sem_t_id = semget(T_KEY, 1, 0666 | IPC_CREAT); if ( !set_semvalue(sem_s_id, S_LOCKOUT_NUMBER) ) { fprintf(stderr, "Failed to Initialize Semaphore S\n"); exit(EXIT_FAILURE); } if ( !set_semvalue(sem_e_id, E_LOCKOUT_NUMBER) ) { fprintf(stderr, "Failed to Initialize Semaphore E\n"); exit(EXIT_FAILURE); } if ( !set_semvalue(sem_n_id, N_LOCKOUT_NUMBER) ) { fprintf(stderr, "Failed to Initialize Semaphore N\n"); exit(EXIT_FAILURE); } if ( !set_semvalue(sem_t_id, T_LOCKOUT_NUMBER) ) { fprintf(stderr, "Failed to Initialize Semaphore T\n"); exit(EXIT_FAILURE); } /* Shared Memory */ if ( (shmid = shmget((key_t)SHM_KEY, sizeof(circular_buf_st), 0666 | IPC_CREAT)) == -1 ) { fprintf(stderr, "Shared Memory Get Failed\n"); exit(EXIT_FAILURE); } if ( (shared_memory = shmat(shmid, (void *)0, 0)) == ((void *)-1) ) { fprintf(stderr, "Shared Memory Attach Failed\n"); exit(EXIT_FAILURE); } shared_buffer = (circular_buf_st *) shared_memory; /* Producer */ if ( (file_input = open(FILE_INPUT, O_RDONLY)) == -1) { fprintf(stderr,"Failed to Open File Input\n"); exit(EXIT_FAILURE); } /* gets file stats */ struct stat st; stat(FILE_INPUT, &st); shared_buffer -> file_size = st.st_size; printf("File Size: %d\n", shared_buffer -> file_size); sem_signal(sem_t_id); //Start Time gettimeofday(&start, NULL); while( (bytes_copied = read(file_input, file_data, BUFSIZ)) != 0 ) { if (bytes_copied < 0) { fprintf(stderr, "Error when reading from file\n"); exit(EXIT_FAILURE); } //size of data already copied to shared mem int size = 0; while(bytes_copied > size){ //copying files from read file to a buffer that will be sent to shared memory. strncpy(data, file_data+size, OUR_BUFSIZ); size += OUR_BUFSIZ; int to_copy = OUR_BUFSIZ; //checking case where the data isn't OUR_BUFSIZ size if(size>bytes_copied) to_copy -=(size-bytes_copied); sem_wait(sem_e_id); sem_wait(sem_s_id); //clearing shared memory shared_buffer -> shared_mem[buf_index].count = 0; memset( shared_buffer -> shared_mem[buf_index].buffer, 0, sizeof(shared_buffer -> shared_mem[buf_index].buffer)); //adding data to shared memory shared_buffer -> shared_mem[buf_index].count = to_copy; // Set the count of copied bytes strncpy( shared_buffer -> shared_mem[buf_index].buffer, data, to_copy ); // Copy the read data sem_signal(sem_s_id); sem_signal(sem_n_id); if (++buf_index == NUMBER_OF_BUFFERS) buf_index = 0; // Increment buffer index memset(data, '\0', sizeof(data)); } } //End Time gettimeofday(&end, NULL); printf("Number of Bytes Copied to shared Memory = %d\n", st.st_size); printf("Producer Elapsed Time: %ld microseconds\n\n", ((end.tv_sec * MICRO_SEC_IN_SEC + end.tv_usec) - (start.tv_sec * MICRO_SEC_IN_SEC + start.tv_usec))); shmdt(shared_memory); close(file_input); exit(EXIT_SUCCESS); }