static int doTerminateInstance( struct nc_state_t *nc, ncMetadata *meta, char *instanceId, int *shutdownState, int *previousState) { ncInstance *instance, *vninstance; virConnectPtr *conn; int err; sem_p (inst_sem); instance = find_instance(&global_instances, instanceId); sem_v (inst_sem); if (instance == NULL) return NOT_FOUND; /* try stopping the KVM domain */ conn = check_hypervisor_conn(); if (conn) { sem_p(hyp_sem); virDomainPtr dom = virDomainLookupByName(*conn, instanceId); sem_v(hyp_sem); if (dom) { /* also protect 'destroy' commands, just in case */ sem_p (hyp_sem); err = virDomainDestroy (dom); sem_v (hyp_sem); if (err==0) { logprintfl (EUCAINFO, "destroyed domain for instance %s\n", instanceId); } sem_p(hyp_sem); virDomainFree(dom); /* necessary? */ sem_v(hyp_sem); } else { if (instance->state != BOOTING) logprintfl (EUCAWARN, "warning: domain %s to be terminated not running on hypervisor\n", instanceId); } } /* change the state and let the monitoring_thread clean up state */ sem_p (inst_sem); if (instance->state==BOOTING) { change_state (instance, CANCELED); } else { change_state (instance, SHUTOFF); } sem_v (inst_sem); *previousState = instance->stateCode; *shutdownState = instance->stateCode; return OK; }
int main(int argc, char *argv[]) { //前面一大块4个人物其实都是一样的,就是看看semget是不是分配成功,共享区是不是分享成功 int i,item,shmid; semaphore mutex,pan,orange; union semun sem_union; void *shared_memory = (void *)0; struct shared_use_st *shared_stuff; if ( (mutex=semget((key_t)KEY_MUTEX,1,0666|IPC_CREAT)) == -1 ) { fprintf(stderr,"Failed to create semaphore!"); exit(EXIT_FAILURE); } if ( (pan = semget((key_t)KEY_PAN,1,0666|IPC_CREAT)) == -1 ) { fprintf(stderr,"Failed to create semaphore!"); exit(EXIT_FAILURE); } if ( (orange = semget((key_t)KEY_ORANGE,1,0666|IPC_CREAT)) == -1 ) { fprintf(stderr,"Failed to create semaphore!"); exit(EXIT_FAILURE); } if ( (shmid = shmget((key_t)KEY_SHM,sizeof(struct shared_use_st),0666|IPC_CREAT)) == -1 ) { fprintf(stderr,"Failed to create shared memory!"); exit(EXIT_FAILURE); } if ( (shared_memory = shmat(shmid,(void *)0,0) ) == (void *)-1) { fprintf(stderr,"shmat failed\n"); exit(EXIT_FAILURE); } shared_stuff = (struct shared_use_st *)shared_memory; //这个是模仿老师的30个,其实通过sleep的时间调整,能让dad和mother经常拿到不同盘子,比较接近的话,会一直拿到一样的盘子的 for(i=0;i<30;i++) { sleep(0.9); sem_p(pan); sem_p(mutex); (shared_stuff->hi) = ((shared_stuff->hi)+1) % BUFFER_SIZE; item = ((int)shared_stuff->hi)+1; printf("Mother use pan %d put the orange\n",item); sem_v(mutex); sem_v(orange); } if (shmdt(shared_memory) == -1) { fprintf(stderr, "shmdt failed\n"); exit(EXIT_FAILURE); } printf("Finish!\n"); getchar(); exit(EXIT_SUCCESS); }
int diskutil_loop (const char * path, const long long offset, char * lodev, int lodev_size) { int found = 0; int done = 0; int ret = OK; char * output; // we retry because we cannot atomically obtain a free loopback // device on all distros (some versions of 'losetup' allow a file // argument with '-f' options, but some do not) for (int i=0; i<LOOP_RETRIES; i++) { sem_p (loop_sem); output = pruntf (TRUE, "%s %s -f", helpers_path[ROOTWRAP], helpers_path[LOSETUP]); sem_v (loop_sem); if (output==NULL) // there was a problem break; if (strstr (output, "/dev/loop")) { strncpy (lodev, output, lodev_size); char * ptr = strrchr (lodev, '\n'); if (ptr) { *ptr = '\0'; found = 1; } } free (output); if (found) { boolean do_log = ((i+1)==LOOP_RETRIES); // log error on last try only logprintfl (EUCADEBUG, "{%u} attaching file %s\n", (unsigned int)pthread_self(), path); logprintfl (EUCADEBUG, "{%u} to %s at offset %lld\n", (unsigned int)pthread_self(), lodev, offset); sem_p (loop_sem); output = pruntf (do_log, "%s %s -o %lld %s %s", helpers_path[ROOTWRAP], helpers_path[LOSETUP], offset, lodev, path); sem_v (loop_sem); if (output==NULL) { logprintfl (EUCADEBUG, "{%u} cannot attach to loop device %s (will retry)\n", (unsigned int)pthread_self(), lodev); } else { free (output); done = 1; break; } } sleep (1); found = 0; } if (!done) { logprintfl (EUCAINFO, "{%u} error: cannot find free loop device or attach to one\n", (unsigned int)pthread_self()); ret = ERROR; } return ret; }
static int doAttachSystemDisk ( struct nc_state_t *nc, ncMetadata *meta, char *instanceId, char *isoPath) { ncInstance *instance; virConnectPtr *conn; virDomainPtr dom = NULL; char xml[MAX_PATH]={'\0'}; int err; snprintf (xml, sizeof(xml), "<disk type='block' device='cdrom'><source dev='%s'/><target dev='hdc' bus='ide'/><readonly/></disk>", isoPath); //logprintfl(EUCAINFO, "doAttachSystemDisk(): founded %s [%s---%s---%d]\n", instanceId,__FILE__, __FUNCTION__, __LINE__); sem_p(inst_sem); instance = find_instance(&global_instances, instanceId); sem_v(inst_sem); if (instance == NULL || (instance->state != RUNNING&& instance->state != BLOCKED&& instance->state !=PAUSED)) { logprintfl(EUCAINFO, "doAttachSystemDisk(): found %s failed or instance->state!=RUNNING||BLOCKED||PAUSED [file:%s---line:%d]\n", instanceId, __FILE__, __LINE__); return NOT_FOUND; } conn = check_hypervisor_conn(); if (conn) { /* snprintf(cmd, sizeof(cmd), "virsh attach-disk %s %s hdc --type cdrom --mode readonly",instanceId, isoPath); logprintfl(EUCAINFO, "xiongm: cmd=%s [%s---%s---%d]\n",cmd, __FILE__, __FUNCTION__, __LINE__); system(cmd); */ dom = NULL; sem_p(hyp_sem); dom = virDomainLookupByName(*conn, instanceId); sem_v(hyp_sem); if (dom) { sem_p (hyp_sem); err = virDomainAttachDevice (dom, xml); sem_v (hyp_sem); if(err != 0) { logprintfl(EUCAINFO,"virDomainAttachDevice failed. err=%d\n",err); return 1; } } logprintfl(EUCAINFO,"doAttachSystemDisk success.\n"); return 0; } else { logprintfl(EUCAINFO, "doAttachSystemDisk(): no connect hypervisior [file:%s---line:%d]\n",__FILE__, __LINE__); return 1; } }
//! //! Detach a local device that is iSCSI and disconnect the session. //! //! @param[in] sc_url - The URL to reach the cluster's SC at. //! @param[in] use_ws_sec - boolean to determine use of WS-SEC. //! @param[in] ws_sec_policy_file - Policy file path for WS-SEC //! @param[in] attachment_token - The volume/token string received in the request that will be used //! @param[in] connect_string - The connect string used for attachment, to be re-used on disconnect //! @param[in] local_ip - The local host's external IP //! @param[in] local_iqn - The local host's IQN //! //! @return //! //! @pre //! //! @post //! //! @note should only be invoked after detachment from the guest //! int disconnect_ebs_volume(char *sc_url, int use_ws_sec, char *ws_sec_policy_file, char *attachment_token, char *connect_string, char *local_ip, char *local_iqn) { int ret = EUCA_ERROR; int norescan = 0; //send a 0 to indicate no rescan requested ebs_volume_data *vol_data = NULL; if (attachment_token == NULL || connect_string == NULL || local_ip == NULL || local_iqn == NULL) { LOGERROR("Cannont disconnect ebs volume. Got NULL input parameters.\n"); return EUCA_ERROR; } LOGTRACE("Disconnecting an EBS volume\n"); if (deserialize_volume(attachment_token, &vol_data) != EUCA_OK) { LOGERROR("Could not deserialize attachment token string %s\n", attachment_token); return EUCA_ERROR; } LOGTRACE("Requesting volume lock\n"); sem_p(vol_sem); { LOGTRACE("Got volume lock\n"); ret = cleanup_volume_attachment(sc_url, use_ws_sec, ws_sec_policy_file, vol_data, connect_string, local_ip, local_iqn, norescan); LOGTRACE("cleanup_volume_attachment returned: %d\n", ret); LOGTRACE("Releasing volume lock\n"); } sem_v(vol_sem); LOGTRACE("Released volume lock\n"); EUCA_FREE(vol_data); return ret; }
//! //! Handles the reboot request of an instance. //! //! @param[in] nc a pointer to the NC state structure to initialize //! @param[in] pMeta a pointer to the node controller (NC) metadata structure //! @param[in] instanceId the instance identifier string (i-XXXXXXXX) //! //! @return EUCA_OK on success or proper error code. Known error code returned include: EUCA_ERROR //! and EUCA_FATAL_ERROR. //! static int doRebootInstance(struct nc_state_t *nc, ncMetadata * pMeta, char *instanceId) { pthread_t tcb = { 0 }; ncInstance *instance = NULL; sem_p(inst_sem); { instance = find_instance(&global_instances, instanceId); } sem_v(inst_sem); if (instance == NULL) { logprintfl(EUCAERROR, "[%s] cannot find instance\n", instanceId); return (EUCA_ERROR); } // since shutdown/restart may take a while, we do them in a thread if (pthread_create(&tcb, NULL, rebooting_thread, (void *)instance)) { logprintfl(EUCAERROR, "[%s] failed to spawn a reboot thread\n", instanceId); return (EUCA_FATAL_ERROR); } if (pthread_detach(tcb)) { logprintfl(EUCAERROR, "[%s] failed to detach the rebooting thread\n", instanceId); return (EUCA_FATAL_ERROR); } return (EUCA_OK); }
static int doRebootInstance( struct nc_state_t *nc, ncMetadata *meta, char *instanceId) { sem_p (inst_sem); ncInstance *instance = find_instance (&global_instances, instanceId); sem_v (inst_sem); if ( instance == NULL ) { logprintfl (EUCAERROR, "cannot find instance %s\n", instanceId); return ERROR; } pthread_t tcb; // since shutdown/restart may take a while, we do them in a thread if ( pthread_create (&tcb, NULL, rebooting_thread, (void *)instance) ) { logprintfl (EUCAERROR, "failed to spawn a reboot thread\n"); return ERROR_FATAL; } if (pthread_detach(tcb)) { logprintfl (EUCAERROR, "failed to detach the rebooting thread\n"); return ERROR_FATAL; } return OK; }
int diskutil_unloop (const char * lodev) { int ret = OK; char * output; int retried = 0; logprintfl (EUCADEBUG, "{%u} detaching from loop device %s\n", (unsigned int)pthread_self(), lodev); // we retry because we have seen spurious errors from 'losetup -d' on Xen: // ioctl: LOOP_CLR_FD: Device or resource bus for (int i=0; i<LOOP_RETRIES; i++) { boolean do_log = ((i+1)==LOOP_RETRIES); // log error on last try only sem_p (loop_sem); output = pruntf (do_log, "%s %s -d %s", helpers_path[ROOTWRAP], helpers_path[LOSETUP], lodev); sem_v (loop_sem); if (!output) { ret = ERROR; } else { ret = OK; free (output); break; } logprintfl (EUCADEBUG, "{%u} cannot detach loop device %s (will retry)\n", (unsigned int)pthread_self(), lodev); retried++; sleep (1); } if (ret == ERROR) { logprintfl (EUCAWARN, "{%u} error: cannot detach loop device\n", (unsigned int)pthread_self()); } else if (retried) { logprintfl (EUCAINFO, "{%u} succeeded to detach %s after %d retries\n", (unsigned int)pthread_self(), lodev, retried); } return ret; }
int sem_down(struct proc *p, int sem) { if (sem < 0) { fprintf(stderr, "sem_down: Invalid semaphor (pid %u)\n", p->pid); return 1; } switch (sem_p(sem)) { case -1: fprintf(stderr, "sem_down: error putting semaphor down (pid %u)\n", p->pid); return 1; case 0: return 0; case 1: if (retry_op(p) != 0) { fprintf(stderr, "sem_down: error resetting IC (pid %u)\n", p->pid); return 1; } sched_suspend(p->pid); if (insert_proc(&sem_wq[sem], p) != 0) { fprintf(stderr, "sem_down: error adding self to wait queue (pid %u)\n", p->pid); return 1; } return 0; default: fprintf(stderr, "sem_down: unexpected value returned from p() (pid %u)\n", p->pid); return 1; } }
//! //! Handles the reboot request of an instance. //! //! @param[in] nc a pointer to the NC state structure to initialize //! @param[in] pMeta a pointer to the node controller (NC) metadata structure //! @param[in] instanceId the instance identifier string (i-XXXXXXXX) //! //! @return EUCA_OK on success or proper error code. Known error code returned include: //! EUCA_ERROR, EUCA_NOT_FOUND_ERROR, and EUCA_FATAL_ERROR. //! static int doRebootInstance(struct nc_state_t *nc, ncMetadata * pMeta, char *instanceId) { pthread_t tcb = { 0 }; ncInstance *instance = NULL; rebooting_thread_params *params = NULL; sem_p(inst_sem); { instance = find_instance(&global_instances, instanceId); } sem_v(inst_sem); if (instance == NULL) { LOGERROR("[%s] cannot find instance\n", instanceId); return (EUCA_NOT_FOUND_ERROR); } params = EUCA_ZALLOC(1, sizeof(rebooting_thread_params)); memcpy(&(params->instance), instance, sizeof(ncInstance)); memcpy(&(params->nc), nc, sizeof(struct nc_state_t)); // since shutdown/restart may take a while, we do them in a thread if (pthread_create(&tcb, NULL, rebooting_thread, params)) { LOGERROR("[%s] failed to spawn a reboot thread\n", instanceId); return (EUCA_FATAL_ERROR); } set_corrid_pthread(get_corrid() != NULL ? get_corrid()->correlation_id : NULL, tcb); if (pthread_detach(tcb)) { LOGERROR("[%s] failed to detach the rebooting thread\n", instanceId); return (EUCA_FATAL_ERROR); } return (EUCA_OK); }
int disconnect_iscsi_target (const char *dev_string) { int pid, retval, status; assert (strlen (home)); logprintfl (EUCAINFO, "disconnect_iscsi_target invoked (dev_string=%s)\n", dev_string); sem_p (iscsi_sem); pid = fork(); if (!pid) { if ( dev_string && strlen(dev_string) ) logprintfl(EUCADEBUG, "disconnect_iscsi_target(): running command: %s %s,%s\n", disconnect_storage_cmd_path, home, dev_string); if (vrun("%s %s,%s", disconnect_storage_cmd_path, home, dev_string) != 0) { logprintfl (EUCAERROR, "ERROR: disconnect_iscsi_target failed\n"); exit(1); } exit(0); } else { retval = timewait(pid, &status, 90); if (retval) { retval = WEXITSTATUS(status); } else { kill(pid, SIGKILL); retval = -1; } } sem_v (iscsi_sem); return retval; }
int main() { int semid, shmid; char *shmaddr; if ((shmid = createshm(".", 'm', SHM_SIZE)) == -1){ exit (1); } if((shmaddr = shmat (shmid, (char *)0, 0)) == (char *)-1){ perror ("attach shared memory error!\n"); exit (1); } if((semid = opensem("." ,'s')) == -1){ exit (1); } while(1){ printf("reader: "); sem_p(semid,0); /* P操作 */ printf("%s", shmaddr); sem_v(semid,0); /* V操作 */ } }
/* wait for file 'appear' to appear or for file 'disappear' to disappear */ static int wait_for_file (const char * appear, const char * disappear, const int iterations, const char * name) { int done, i; if (!appear && !disappear) return 1; for ( i=0, done=0; i<iterations && !done; i++ ) { struct stat mystat; sem_p (sc_sem); int check = ( (appear && (stat (appear, &mystat)==0)) || (disappear && (stat (disappear, &mystat)!=0)) ); sem_v (sc_sem); if (check) { done++; } else { if (i==0) { logprintfl (EUCAINFO, "waiting for %s to become ready...\n", name); } sleep (10); } } if (!done) { logprintfl (EUCAERROR, "ERROR: timed out waiting for %s to become ready\n", name); return 1; } return 0; }
int create_instance_backing (ncInstance * instance) { int ret = ERROR; virtualMachine * vm = &(instance->params); artifact * sentinel = NULL; // ensure instance directory exists set_path (instance->instancePath, sizeof (instance->instancePath), instance, NULL); if (ensure_directories_exist (instance->instancePath, 0, NULL, "root", BACKING_DIRECTORY_PERM) == -1) goto out; // set various instance-directory-relative paths in the instance struct set_path (instance->xmlFilePath, sizeof (instance->xmlFilePath), instance, "instance.xml"); set_path (instance->libvirtFilePath, sizeof (instance->libvirtFilePath), instance, "libvirt.xml"); set_path (instance->consoleFilePath, sizeof (instance->consoleFilePath), instance, "console.log"); if (strstr (instance->platform, "windows")) { // generate the floppy file for windows instances if (makeWindowsFloppy (nc_state.home, instance->instancePath, instance->keyName, instance->instanceId)) { logprintfl (EUCAERROR, "[%s] error: could not create windows bootup script floppy\n", instance->instanceId); goto out; } else { set_path (instance->floppyFilePath, sizeof (instance->floppyFilePath), instance, "floppy"); } } char work_prefix [1024]; // {userId}/{instanceId} set_id (instance, NULL, work_prefix, sizeof (work_prefix)); // compute tree of dependencies sentinel = vbr_alloc_tree (vm, // the struct containing the VBR FALSE, // for Xen and KVM we do not need to make disk bootable TRUE, // make working copy of runtime-modifiable files (instance->do_inject_key)?(instance->keyName):(NULL), // the SSH key instance->instanceId); // ID is for logging if (sentinel == NULL) { logprintfl (EUCAERROR, "[%s] error: failed to prepare backing for instance\n", instance->instanceId); goto out; } sem_p (disk_sem); // download/create/combine the dependencies int rc = art_implement_tree (sentinel, work_bs, cache_bs, work_prefix, INSTANCE_PREP_TIMEOUT_USEC); sem_v (disk_sem); if (rc != OK) { logprintfl (EUCAERROR, "[%s] error: failed to implement backing for instance\n", instance->instanceId); goto out; } if (save_instance_struct (instance)) // update instance checkpoint now that the struct got updated goto out; ret = OK; out: if (sentinel) art_free (sentinel); return ret; }
/** Searches the processor state array for a free processor (state <= 0). @param states The array of processor states. Each cell <i>i</i> contains a key such that:<br> <ul><li>If <b>key < 0</b>, processor has completed the |key|-th operation <li>If <b>key == 0</b>, processor has not received an operation yet <li>If <b>key > 0</b>, processor is currently working on the key-th operation</ul> @return The ID of a free processor */ static int find_proc(int *states) { int i = 0; sem_p(2 * processors); write_to_fd(1, "Looking for a free processor\n"); while(states[i++] > 0); sem_v(2 * processors); write_with_int(1, "Found processor ", i); return i - 1; }
void staebchen_weglegen(int my_id, int pos) { printf("%i legt %i weg\n", my_id, pos); if (staebchen[pos]!=0) { printf("Fehler: staebchen[%i]=%i statt 0\n", pos, staebchen[pos]); exit(1); } sem_p(sem[pos]); staebchen[pos]++; // ergibt 1, gibt aber chance zur fehlererkennung sem_v(sem[pos]); }
int main() { int i, item, shmid; semaphore mutex; semaphore dif1; semaphore dif2; void* shared_memory = NULL; struct shared_use_st* shared_stuff = NULL; if ((mutex = semget((key_t)KEY_MUTEX, 1, 0666|IPC_CREAT)) == -1) { fprintf(stderr, "Failed to create semaphore!\n"); exit(EXIT_FAILURE); } if ((dif1 = semget((key_t)KEY_EMPTY, 1, 0666|IPC_CREAT)) == -1) { fprintf(stderr, "Failed to create semaphore!\n"); exit(EXIT_FAILURE); } if ((dif2 = semget((key_t)KEY_FULL, 1, 0666|IPC_CREAT)) == -1) { fprintf(stderr, "Failed to create semaphore!\n"); exit(EXIT_FAILURE); } if ((shmid = shmget((key_t)KEY_SHM, 1, 0666|IPC_CREAT)) == -1) { fprintf(stderr, "Failed to create semaphore!\n"); exit(EXIT_FAILURE); } if ((shared_memory = shmat(shmid, NULL, 0)) == (void*)(-1)) { fprintf(stderr, "shmat failed!\n"); exit(EXIT_FAILURE); } shared_stuff = (struct shared_use_st*)shared_memory; for (i = 0; i < 30; ++i) { sleep(1); sem_p(dif2); sem_p(mutex); shared_stuff->high++; print(shared_stuff); sem_v(dif1); sem_v(mutex); } exit(EXIT_SUCCESS); }
static int doRestoreAInstance(struct nc_state_t *nc, ncMetadata *meta, char *instanceId) { sem_p(inst_sem); ncInstance *instance = find_instance(&global_instances, instanceId); sem_v(inst_sem); if (instance == NULL || (instance->state != SHUTOFF && instance->state != TRASHED)) { logprintfl(EUCAINFO, "doRestoreAInstance: found instance %s in global_instances error or instance->state!=SHUTOFF||TRASHED \n", instanceId); return NOT_FOUND; } if(instance->state == SHUTOFF) { pthread_t tcb; if(pthread_create(&tcb, NULL, restoring_thread, (void *)instance)) { logprintfl (EUCAERROR, "failed to spawn a restore thread\n"); return ERROR_FATAL; } if (pthread_detach(tcb)) { logprintfl (EUCAERROR, "failed to detach the restoring thread\n"); return ERROR_FATAL; } } else { //instance->state == TRASHED sem_p (inst_sem); change_state(instance,SHUTOFF); save_instance_struct(instance); sem_v (inst_sem); logprintfl(EUCAINFO, "doRestoreAInstance restore instance form TRASHED TO SHUTOFF success next to running it instanceId=%s \n", instanceId); //add 20130106-xm pthread_t tcb; if(pthread_create(&tcb, NULL, restoring_thread, (void *)instance)) { logprintfl (EUCAERROR, "failed to spawn a restore thread\n"); return ERROR_FATAL; } if (pthread_detach(tcb)) { logprintfl (EUCAERROR, "failed to detach the restoring thread\n"); return ERROR_FATAL; } // end 20130106-xm } return OK; }
//---------------------------------------------------------------------------------------------------------------- void busy_child_routine_2(int child_id){ // attende che abbia finito il calcolo print_parent_info(""PARENT" waiting that child %d finish to process the operation\n", child_id); sem_p(sem_computing, child_id); // richiede eventuali dati precedenti print_parent_info(""PARENT" request the result to child %d\n", child_id); sem_v(sem_request_result, child_id); //aspetta che i dati siano pronti da leggere print_parent_info(""PARENT" waiting for result from child %d ...\n", child_id); sem_p(sem_parent, 1); //print_parent_info(""PARENT" saving the result of opration processed from child %d...\n", child_id); }
int main(int argc, char *argv[]) { int opt; opt = getopt(argc, argv, "cdpvs:gfm:"); if (opt == '?') exit(EXIT_FAILURE); if (opt == -1) { usage(); exit(EXIT_FAILURE); } key_t key = ftok(".", 's'); int semid; switch (opt) { case 'c': sem_create(key); break; case 'p': semid = sem_open(key); sem_p(semid); sem_getval(semid); break; case 'v': semid = sem_open(key); sem_v(semid); sem_getval(semid); break; case 'd': semid = sem_open(key); sem_d(semid); break; case 's': semid = sem_open(key); sem_setval(semid, atoi(optarg)); break; case 'g': semid = sem_open(key); sem_getval(semid); break; case 'f': semid = sem_open(key); sem_getmode(semid); break; case 'm': semid = sem_open(key); sem_setmode(semid, argv[2]); break; } return 0; }
int OptLogGet(ST_OptLogCfgData *val) { if (!val || !gendata.cfg) { return -1; } sem_p(gendata.semid); memcpy(val,gendata.cfg,sizeof(ST_OptLogCfgData)); sem_v(gendata.semid); return 0; }
int main(void) { int semid = -1; int pid = -1; /*1.申请信号量 */ semid = semget(ftok(".", 'b'), 1, IPC_CREAT|0666); if(semid < 0) { perror("semget error"); exit(1); } /* 2.初始化信号量 */ init_sem(semid, 0, 1); //资源初始化成可用 /*创建子进程 */ if( (pid = fork()) <0) { perror("fork"); exit(1); } if(pid >0) { //父进程 sem_p(semid, 0, 1); //P操作 //操作资源 //... sem_v(semid, 0, 1); //V操作 } else { //子进程 sem_p(semid, 0, 1); //P操作 //操作资源 //... sem_v(semid, 0, 1); //V操作 //删除信号量 del_sem(semid); } return 0; }
/************************************************************************************************** * function : event log thread * para : {void} * * return : {void} * * history : {2013.7.25 wujun} frist create; **************************************************************************************************/ void log() { initEventLog(); while(1) { delay(); sem_p(giSemLog);//lock writeEventLog(UPLOAD_LOG_FILE, DOWNLOAD_LOG_FILE); sem_v(giSemLog);//unlock } }
static int doRebootInstance( struct nc_state_t *nc, ncMetadata *meta, char *instanceId) { ncInstance *instance; virConnectPtr *conn; sem_p (inst_sem); instance = find_instance(&global_instances, instanceId); sem_v (inst_sem); if ( instance == NULL ) return NOT_FOUND; /* reboot the Xen domain */ conn = check_hypervisor_conn(); if (conn) { sem_p(hyp_sem); virDomainPtr dom = virDomainLookupByName(*conn, instanceId); sem_v(hyp_sem); if (dom) { /* also protect 'reboot', just in case */ sem_p (hyp_sem); int err=virDomainReboot (dom, 0); sem_v (hyp_sem); if (err==0) { logprintfl (EUCAINFO, "[%s] rebooting Xen domain for instance\n", instanceId); } sem_p(hyp_sem); virDomainFree(dom); /* necessary? */ sem_v(hyp_sem); } else { if (instance->state != BOOTING && instance->state != STAGING) { logprintfl (EUCAWARN, "[%s] domain to be rebooted not running on hypervisor\n", instanceId); } } } return 0; }
static int doDescribeInstances( struct nc_state_t *nc, ncMetadata *meta, char **instIds, int instIdsLen, ncInstance ***outInsts, int *outInstsLen) { ncInstance *instance; int total, i, j, k; *outInstsLen = 0; *outInsts = NULL; sem_p (inst_sem); if (instIdsLen == 0) /* describe all instances */ total = total_instances (&global_instances); else total = instIdsLen; *outInsts = malloc(sizeof(ncInstance *)*total); if ((*outInsts) == NULL) { sem_v (inst_sem); return OUT_OF_MEMORY; } k = 0; for (i=0; (instance = get_instance(&global_instances)) != NULL; i++) { /* only pick ones the user (or admin) is allowed to see */ if (strcmp(meta->userId, nc->admin_user_id) && strcmp(meta->userId, instance->userId)) continue; if (instIdsLen > 0) { for (j=0; j < instIdsLen; j++) if (!strcmp(instance->instanceId, instIds[j])) break; if (j >= instIdsLen) /* instance of not relavance right now */ continue; } (* outInsts)[k++] = instance; } *outInstsLen = k; sem_v (inst_sem); return OK; }
int main() { int nsems=1; int sem_id =sem_create(nsems) sleep(20); sem_init(sem_id, 0, 1); sem_p(sem_id, 0); sleep(1); sem_v(sem_id, 0); sem_detroy(sem_id); return 0; }
int diskutil_umount (const char * dev) { int ret = OK; char * output; sem_p (loop_sem); output = pruntf (TRUE, "%s %s umount %s", helpers_path[ROOTWRAP], helpers_path[MOUNTWRAP], dev); sem_v (loop_sem); if (!output) { logprintfl (EUCAINFO, "{%u} error: cannot unmount device '%s'\n", (unsigned int)pthread_self(), dev); ret = ERROR; } else { free (output); } return ret; }
int staebchen_nehmen(int my_id, int pos) { sem_p(sem[pos]); int n=staebchen[pos]; if (n==1) { printf("%i nimmt %i\n", my_id, pos); staebchen[pos]--; // ergibt 0, gibt aber chance zur fehlererkennung sem_v(sem[pos]); return 1; } else if (n==0) { sem_v(sem[pos]); return 0; } else { printf("Fehler: staebchen[%i]=%i\n", pos, n); sem_v(sem[pos]); exit(1); } }
int diskutil_tune (const char * lodev) { int ret = OK; char * output; sem_p (loop_sem); output = pruntf (TRUE, "%s %s %s -c 0 -i 0", helpers_path[ROOTWRAP], helpers_path[TUNE2FS], lodev); sem_v (loop_sem); if (!output) { logprintfl (EUCAINFO, "{%u} error: cannot tune file system on '%s'\n", (unsigned int)pthread_self(), lodev); ret = ERROR; } else { free (output); } return ret; }
int diskutil_umount (const char * dev) { int ret = OK; char * output; sem_p (loop_sem); output = pruntf (TRUE, "%s %s umount %s", helpers_path[ROOTWRAP], helpers_path[MOUNTWRAP], dev); sem_v (loop_sem); if (!output) { logprintfl (EUCAERROR, "cannot unmount device '%s'\n", dev); ret = ERROR; } else { free (output); } return ret; }