Search Results

Search found 2363 results on 95 pages for 'sleep'.

Page 32/95 | < Previous Page | 28 29 30 31 32 33 34 35 36 37 38 39  | Next Page >

  • How do I browse a Websphere MQ message without removing it?

    - by jmgant
    I'm writing a .NET Windows Forms application that will post a message to a Websphere MQ queue and then poll a different queue for a response. If a response is returned, the application will partially process the response in real time. But the response needs to stay in the queue so that a daily batch job, which also reads from the response queue, can do the rest of the processing. I've gotten as far as reading the message. What I haven't been able to figure out is how to read it without removing it. Here's what I've got so far. I'm an MQ newbie, so any suggestions will be appreciated. And feel free to respond in C#. Public Function GetMessage(ByVal msgID As String) As MQMessage Dim q = ConnectToResponseQueue() Dim msg As New MQMessage() Dim getOpts As New MQGetMessageOptions() Dim runThru = Now.AddMilliseconds(CInt(ConfigurationManager.AppSettings("responseTimeoutMS"))) System.Threading.Thread.Sleep(1000) 'Wait for one second before checking for the first response' While True Try q.Get(msg, getOpts) Return msg Catch ex As MQException When ex.Reason = MQC.MQRC_NO_MSG_AVAILABLE If Now > runThru Then Throw ex System.Threading.Thread.Sleep(3000) Finally q.Close() End Try End While Return Nothing 'Should never reach here' End Function NOTE: I haven't verified that my code actually removes the message. But that's how I understand MQ to work, and that appears to be what's happening. Please correct me if that's not the default behavior.

    Read the article

  • Application crashing on getting updated information from database using timer and storing it on loca

    - by Amit Battan
    In our multi - user application we are continuously interacting with database. We have a common class through which we are sending POST queries to database and obtaining xml files in return. We are using delegates of NSXMLParser to parse the obtained file. The problem with us is we are facing many crashes in it generally when application is idle and changed data in database is being fetched in background through timer which is invoked after every few seconds. We have also dealt with error handling through try and catch but it proves to be of no use in this case and mostly application crashes with following error : Exception Type: EXC_BAD_ACCESS (SIGBUS) Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000000000020 Strange thing is that many times the fetching of updated data at background works very fine, same methods being successfully executed under similar conditions but suddenly it crashes on one of them. The codes we are using is as follows: // we are using timer in this way: chkOnlineUser=[NSTimer scheduledTimerWithTimeInterval:15 target:mmObject selector:@selector(threadOnlineUser) userInfo:NULL repeats:YES]; // this method being called in timer -(void)threadOnlineUser{//HeartBeat in Thread [NSThread detachNewThreadSelector:@selector(onlineUserRefresh) toTarget:self withObject:nil]; } // this performs actual updation -(void)onlineUserRefresh{ NSAutoreleasePool *pool =[[NSAutoreleasePool alloc]init]; @try{ if(chkTimer==1){ return; } chkTimer=1; if([allUserArray count]==0){ [user parseXMLFileUser:@"all" andFlag:3]; [allUserArray removeAllObjects]; [allUserArray addObjectsFromArray:[user users]]; } [objHeartBeat parseXMLFile:[loginID intValue] timeOut:10]; NSMutableDictionary *tDictOL=[[NSMutableDictionary alloc] init]; tDictOL=[objHeartBeat onLineList]; NSArray *tArray=[[NSArray alloc] init]; tArray=[[tDictOL objectForKey:@"onlineuser"] componentsSeparatedByString:@","]; [loginUserArray removeAllObjects]; for(int l=0;l less than [tArray count] ;l++){ int t;//=[[tArray objectAtIndex:l] intValue]; if([[allUserArray valueForKey:@"Id"] containsObject:[tArray objectAtIndex:l]]){ t = [[allUserArray valueForKey:@"Id"] indexOfObject:[tArray objectAtIndex:l]]; [loginUserArray addObject:[allUserArray objectAtIndex:t]]; } } [onlineTable reloadData]; [logInUserPopUp removeAllItems]; if([loginUserArray count]==1){ [labelLoginUser setStringValue:@"Only you are online"]; [logInUserPopUp setEnabled:YES]; }else{ [labelLoginUser setStringValue:[NSString stringWithFormat:@" %d users online",[loginUserArray count]]]; [logInUserPopUp setEnabled:YES]; } NSMenu *menu = [[NSMenu alloc] initWithTitle:@"menu"]; NSMenuItem *itemOne = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""]; [menu addItem:itemOne]; for(int l=0;l less than [loginUserArray count];l++){ NSString *tempStr= [NSString stringWithFormat:@"%@ %@",[[[loginUserArray objectAtIndex:l] objectForKey:@"user_fname"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]],[[[loginUserArray objectAtIndex:l] objectForKey:@"user_lname"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]]; if(![tempStr isEqualToString:@""]){ NSMenuItem *itemOne = [[NSMenuItem alloc] initWithTitle:tempStr action:NULL keyEquivalent:@""]; [menu addItem:itemOne]; }else if(l==0){ NSMenuItem *itemOne = [[NSMenuItem alloc] initWithTitle:tempStr action:NULL keyEquivalent:@""]; [menu addItem:itemOne]; } } [logInUserPopUp setMenu:menu]; if([lastUpdateTime isEqualToString:@""]){ }else { [self fetchUpdatedInfo:lastUpdateTime]; [self fetchUpdatedGroup:lastUpdateTime];// function same as fetchUpdatedInfo [avObject fetchUpdatedInfo:lastUpdateTime];// function same as fetchUpdatedInfo [esTVObject fetchUpdatedInfo:lastUpdateTime];// function same as fetchUpdatedInfo } lastUpdateTime=[[tDictOL objectForKey:@"lastServerTime"] copy]; } @catch (NSException * e) { [queryByPost insertException:@"MainModule" inFun:@"onlineUserRefresh" excp:[e description] userId:[loginID intValue]]; NSRunAlertPanel(@"Error Panel", @"Main Module- onlineUserRefresh....%@", @"OK", nil, nil,e); } @finally { NSLog(@"Internal Update Before Bye"); chkTimer=0; NSLog(@"Internal Update Bye");// Some time application crashes after this log // Some time application crahses after "Internal Update Bye" log } } // The method which we are using to obtain updated data is of following form: -(void)fetchUpdatedInfo:(NSString *)UpdTime{ @try { if(initAfterLoginComplete==0){ return; } [user parseXMLFileUser:UpdTime andFlag:[loginID intValue]]; [tempUserUpdatedArray removeAllObjects]; [tempUserUpdatedArray addObjectsFromArray:[user users]]; if([tempUserUpdatedArray count]0){ if([contactsView isHidden]){ [topContactImg setImage:[NSImage imageNamed:@"btn_contacts_off_red.png"]]; }else { [topContactImg setImage:[NSImage imageNamed:@"btn_contacts_red.png"]]; } }else { return; } int chkprof=0; for(int l=0;l less than [tempUserUpdatedArray count];l++){ NSArray *tempArr1 = [allUserArray valueForKey:@"Id"]; int s; if([[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"] intValue]==profile_Id){ chkprof=1; } if([tempArr1 containsObject:[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"]]){ s = [tempArr1 indexOfObject:[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"]]; [allUserArray replaceObjectAtIndex:s withObject:[tempUserUpdatedArray objectAtIndex:l]]; }else { [allUserArray addObject:[tempUserUpdatedArray objectAtIndex:l]]; } NSArray *tempArr2 = [tempUser valueForKey:@"Id"]; if([tempArr2 containsObject:[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"]]){ s = [tempArr2 indexOfObject:[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"]]; [tempUser replaceObjectAtIndex:s withObject:[tempUserUpdatedArray objectAtIndex:l]]; }else { [tempUser addObject:[tempUserUpdatedArray objectAtIndex:l]]; } } NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"user_fname" ascending:YES]; [tempUser sortUsingDescriptors:[NSMutableArray arrayWithObject:sortDescriptor]]; [userListTableView reloadData]; [groupsArray removeAllObjects]; for(int z=0;z less than [tempGroups count];z++){ NSMutableArray *tempMArr=[[NSMutableArray alloc] init]; for(int l=0;l less than [allUserArray count];l++){ if([[[allUserArray objectAtIndex:l] objectForKey:@"GroupId"] intValue]==[[[tempGroups objectAtIndex:z] objectForKey:@"group_id"] intValue]){ [tempMArr addObject:[allUserArray objectAtIndex:l]]; } } [groupsArray insertObject:tempMArr atIndex:z]; [tempMArr release]; tempMArr= nil; } for(int n=0;n less than [tempGroups count];n++){ [[groupsArray objectAtIndex:n] addObject:[tempGroups objectAtIndex:n]]; } [groupsListOV reloadData]; if(chkprof==1){ [self profileShow:profile_Id]; }else { } [self selectUserInTable:0]; }@catch (NSException * e) { NSRunAlertPanel(@"Error Panel", @"%@", @"OK", nil, nil,e); } } // The method which we are using to frame select query and parse obtained data is: -(void)parseXMLForUser:(int)UId stringVar:(NSString*)stringVar{ @try{ if(queryByPost) [queryByPost release]; queryByPost=[QueryByPost new]; // common class used to invoke method to send request via POST method //obtaining data for xml parsing NSString *query=[NSString stringWithFormat:@"Select * from userinfo update_time = '%@' AND NOT owner_id ='%d' ",stringVar,UId]; NSData *obtainedData=[queryByPost executeQuery:query WithAction:@"query"]; // method invoked to perform post query if(obtainedData==nil){ // data not obtained so return return; } // initializing dictionary to be obtained after parsing if(obtainedDictionary) [obtainedDictionary release]; obtainedDictionary=[NSMutableDictionary new]; // xml parsing if (updatedDataParser) // airportsListParser is an NSXMLParser instance variable [updatedDataParser release]; updatedDataParser = [[NSXMLParser alloc] initWithData:obtainedData]; [updatedDataParser setDelegate:self]; [updatedDataParser setShouldResolveExternalEntities:YES]; BOOL success = [updatedDataParser parse]; } @catch (NSException *e) { NSLog(@"wtihin parseXMLForUser- parseXMLForUser:stringVar: - %@",[e description]); } } //The method which will attempt to interact 4 times with server if interaction with it is found to be unsuccessful , is of following form: -(NSData*)executeQuery:(NSString*)query WithAction:(NSString*)doAction{ NSLog(@"within ExecuteQuery:WithAction: Query is: %@ and Action is: %@",query,doAction); NSString *returnResult; @try { NSString *returnResult; NSMutableURLRequest *postRequest; NSError *error; NSData *searchData; NSHTTPURLResponse *response; postRequest=[self directMySQLQuery:query WithAction:doAction]; // this method sends actual POST request NSLog(@"after directMYSQL in QueryByPost- performQuery... ErrorLogMsg"); searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; returnResult = [[NSString alloc] initWithData:searchData encoding:NSASCIIStringEncoding]; NSString *resultToBeCompared=[returnResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSLog(@"result obtained - %@/ resultToBeCompared - %@",returnResult,resultToBeCompared); if(![resultToBeCompared isEqualToString:@""]){ }else { sleep(10); postRequest=[self directMySQLQuery:query WithAction:doAction]; searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; if(![resultToBeCompared isEqualToString:@""]){ }else { sleep(10); postRequest=[self directMySQLQuery:query WithAction:doAction]; searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; if(![resultToBeCompared isEqualToString:@""]){ }else { sleep(10); postRequest=[self directMySQLQuery:query WithAction:doAction]; searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; if(![resultToBeCompared isEqualToString:@""]){ }else { sleep(10); postRequest=[self directMySQLQuery:query WithAction:doAction]; searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; if(![resultToBeCompared isEqualToString:@""]){ }else { return nil; } } } } } returnResult = [[NSString alloc] initWithData:searchData encoding:NSASCIIStringEncoding]; return searchData; } @catch (NSException * e) { NSLog(@"within QueryByPost , execurteQuery:WithAction - %@",[e description]); return nil; } } // The method which sends POST request to server , is of following form: -(NSMutableURLRequest *)directMySQLQuery:(NSString*)query WithAction:(NSString*)doAction{ @try{ NSLog(@"Query is: %@ and Action is: %@",query,doAction); // some pre initialization NSString *stringBoundary,*contentType; NSURL *cgiUrl ; NSMutableURLRequest *postRequest; NSMutableData *postBody; NSString *ans=@"434"; cgiUrl = [NSURL URLWithString:@"http://keysoftwareservices.com/API.php"]; postRequest = [NSMutableURLRequest requestWithURL:cgiUrl]; [postRequest setHTTPMethod:@"POST"]; stringBoundary = [NSString stringWithString:@"0000ABCQueryxxxxxx"]; contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", stringBoundary]; [postRequest addValue:contentType forHTTPHeaderField: @"Content-Type"]; //setting up the body: postBody = [NSMutableData data]; [postBody appendData:[[NSString stringWithFormat:@"\r\n\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"code\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:ans] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"action\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:doAction] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"devmode\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"devmode"]] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"q\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:query] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postRequest setHTTPBody:postBody]; NSLog(@"Direct My SQL ok");// Some time application crashes afte this log //Some time application crashes after "Direct My SQL ok" log return [postRequest mutableCopy]; }@catch (NSException * e) { NSLog(@"NSException %@",e); NSRunAlertPanel(@"Error Panel", @"Within QueryByPost- directMySQLQuery...%@", @"OK", nil, nil,e); return nil; } }

    Read the article

  • How do I update blackberry UI items from a thread?

    - by Andrei T. Ursan
    public class PlayText extends Thread { private int duration; private String text; private PlayerScreen playerscrn; public PlayText(String text, int duration) { this.duration = duration; this.text = text; this.playerscrn = (PlayerScreen)UiApplication.getUiApplication().getActiveScreen(); } public void run() { synchronized(UiApplication.getEventLock()) { try{ RichTextField text1player = new RichTextField(this.text, Field.NON_FOCUSABLE); playerscrn.add(text1player); playerscrn.invalidate(); Thread.sleep(this.duration); RichTextField text2player = new RichTextField("hahhaha", Field.NON_FOCUSABLE); playerscrn.add(text2player); playerscrn.invalidate(); Thread.sleep(1000); RichTextField text3player = new RichTextField("Done", Field.NON_FOCUSABLE); playerscrn.add(text3player); playerscrn.invalidate(); }catch(Exception e){ System.out.println("I HAVE AN ERROR"); } } } } With the above code I'm trying to create a small text player. Instead to get all the text labels one by one, something like display text1player wait this.duration milliseconds display text2player wait 1000 milliseconds display text3player thread done. The screens waits this.duration + 1000 milliseconds and displays all the labels at once. I tried with a runnable and calling .invokeLater or .invokeAndWait but I still get the same behavior, and even if I get dirty like above using synchronized it still doesn't work. Does anyone know how I can display each label at a time? Thank you!

    Read the article

  • Getting progress reports from a layered worker class?

    - by Slashdev
    I have a layered worker class that I'm trying to get progress reports from. What I have looks something like this: public class Form1 { private void Start_Click() { Controller controller = new Controller(); controller.RunProcess(); } } public class Controller { public void RunProcess() { Thread newThread = new Thread(new ThreadStart(DoEverything)); newThread.Start(); } private void DoEverything() { // Commencing operation... Class1 class1 = new Class1(); class1.DoStuff(); Class2 class2 = new Class2(); class2.DoMoreStuff(); } } public class Class1 { public void DoStuff() { // Doing stuff Thread.Sleep(1000); // Want to report progress here } } public class Class2 { public void DoMoreStuff() { // Doing more stuff Thread.Sleep(2000); // Want to report progress here as well } } I've used the BackgroundWorker class before, but I think I need something a bit more free form for something like this. I think I could use a delegate/event solution, but I'm not sure how to apply it here. Let's say I've got a few labels or something on Form1 that I want to be able to update with class1 and class2's progress, what's the best way to do that?

    Read the article

  • StorageClientException: The specified message does not exist?

    - by Aaron
    I have a simple video encoding worker role that pulls messages from a queue encodes a video then uploads the video to storage. Everything seems to be working but occasionally when deleting the message after I am done encoding and uploading I get a "StorageClientException: The specified message does not exist." Although the video is processed, I believe the message is reappearing in the queue because it's not being deleted correctly. Is it possible that another instance of the Worker role is processing and deleting the message? Doesn't the GetMessage() prevent other worker roles from picking up the same message? Am I doing something wrong in the setup of my queue? What could be causing this message to not be found on delete? some code... //onStart() queue setup var queueStorage = _storageAccount.CreateCloudQueueClient(); _queue = queueStorage.GetQueueReference(QueueReference); queueStorage.RetryPolicy = RetryPolicies.Retry(5, new TimeSpan(0, 5, 0)); _queue.CreateIfNotExist(); public override void Run() { while (true) { try { var msg = _queue.GetMessage(new TimeSpan(0, 5, 0)); if (msg != null) { EncodeIt(msg); PostIt(msg); _queue.DeleteMessage(msg); } else { Thread.Sleep(WaitTime); } } catch (StorageClientException exception) { BlobTrace.Write(exception.ToString()); Thread.Sleep(WaitTime); } } }

    Read the article

  • Rack middleware deadlock

    - by Joel
    I include this simple Rack Middleware in a Rails application: class Hello def initialize(app) @app = app end def call(env) [200, {"Content-Type" => "text/html"}, "Hello"] end end Plug it in inside environment.rb: ... Dir.glob("#{RAILS_ROOT}/lib/rack_middleware/*.rb").each do |file| require file end Rails::Initializer.run do |config| config.middleware.use Hello ... I'm using Rails 2.3.5, Webrick 1.3.1, ruby 1.8.7 When the application is started in production mode, everything works as expected - every request is intercepted by the Hello middleware, and "Hello" is returned. However, when run in development mode, the very first request works returning "Hello", but the next request hangs. Interrupting webrick while it is in the hung state yields this: ^C[2010-03-24 14:31:39] INFO going to shutdown ... deadlock 0xb6efbbc0: sleep:- - /usr/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/reloader.rb:31 deadlock 0xb7d1b1b0: sleep:J(0xb6efbbc0) (main) - /usr/lib/ruby/1.8/webrick/server.rb:113 Exiting /usr/lib/ruby/1.8/webrick/server.rb:113:in `join': Thread(0xb7d1b1b0): deadlock (fatal) from /usr/lib/ruby/1.8/webrick/server.rb:113:in `start' from /usr/lib/ruby/1.8/webrick/server.rb:113:in `each' from /usr/lib/ruby/1.8/webrick/server.rb:113:in `start' from /usr/lib/ruby/1.8/webrick/server.rb:23:in `start' from /usr/lib/ruby/1.8/webrick/server.rb:82:in `start' from /usr/lib/ruby/gems/1.8/gems/rack-1.0.1/lib/rack/handler/webrick.rb:14:in `run' from /usr/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/commands/server.rb:111 from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require' from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from script/server:3 Something to do with the class reloader in development mode. There is also mention of deadlock in the exception. Any ideas what might be causing this? Any recommendations as to the best approach to debug this?

    Read the article

  • C# TcpClient, getting back the entire response from a telnet device

    - by Dan Bailiff
    I'm writing a configuration tool for a device that can communicate via telnet. The tool sends a command via TcpClient.GetStream().Write(...), and then checks for the device response via TcpClient.GetStream().ReadByte(). This works fine in unit tests or when I'm stepping through code slowly. If I run the config tool such that it performs multiple commands consecutively, then the behavior of the read is inconsistent. By inconsistent I mean sometimes the data is missing, incomplete or partially garbled. So even though the device performed the operation and responded, my code to check for the response was unreliable. I "fixed" this problem by adding a Thread.Sleep to make sure the read method waits long enough for the device to complete its job and send back the whole response (in this case 1.5 seconds was a safe amount). I feel like this is wrong, blocking everything for a fixed time, and I wonder if there is a better way to get the read method to wait only long enough to get the whole response from the device. private string Read() { if (!tcpClient.Connected) throw (new Exception("Read() failed: Telnet connection not available.")); StringBuilder sb = new StringBuilder(); do { ParseTelnet(ref sb); System.Threading.Thread.Sleep(1500); } while (tcpClient.Available > 0); return sb.ToString(); } private void ParseTelnet(ref StringBuilder sb) { while (tcpClient.Available > 0) { int input = tcpClient.GetStream().ReadByte(); switch (input) { // parse the input // ... do other things in special cases default: sb.Append((char)input); break; } } }

    Read the article

  • Get_user running at kernel mode returns error

    - by Fangkai Yang
    Hi, all, I have a problem with get_user() macro. What I did is as follows: I run the following program int main() { int a = 20; printf("address of a: %p", &a); sleep(200); return 0; } When the program runs, it outputs the address of a, say, 0xbff91914. Then I pass this address to a module running in Kernel Mode that retrieves the contents at this address (at the time when I did this, I also made sure the process didn't terminate, because I put it to sleep for 200 seconds... ): The address is firstly sent as a string, and I cast them into pointer type. int * ptr = (int*)simple_strtol(buffer, NULL,16); printk("address: %p",ptr); // I use this line to make sure the cast is correct. When running, it outputs bff91914, as expected. int val = 0; int res; res= get_user(val, (int*) ptr); However, res is always not 0, meaning that get_user returns error. I am wondering what is the problem.... Thank you!! -- Fangkai

    Read the article

  • confusing fork system call

    - by benjamin button
    Hi, i was just checking the behaviour of fork system call and i found it very confusing. i saw in a website that Unix will make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes have separate address spaces #include <stdio.h> #include <sys/types.h> int main(void) { pid_t pid; char y='Y'; char *ptr; ptr=&y; pid = fork(); if (pid == 0) { y='Z'; printf(" *** Child process ***\n"); printf(" Address is %p\n",ptr); printf(" char value is %c\n",y); sleep(5); } else { sleep(5); printf("\n ***parent process ***\n",&y); printf(" Address is %p\n",ptr); printf(" char value is %c\n",y); } } the output of the above program is : *** Child process *** Address is 69002894 char value is Z ***parent process *** Address is 69002894 char value is Y so from the above mentioned statement it seems that child and parent have separet address spaces.this is the reason why char value is printed separately and why am i seeing the address of the variable as same in both child and parent processes.? Please help me understand this!

    Read the article

  • need help about process........

    - by adeel amin
    when i start process like process= Runtime.getRuntime().exec("gnome-terminal");, it start shell execution, i want to stop shell execution and want to redirect I/O from process, can anybody tell how i can do this? my code is: public void start_process() { try { process= Runtime.getRuntime().exec("bash"); pw= new PrintWriter(process.getOutputStream(),true); br=new BufferedReader(new InputStreamReader(process.getInputStream())); err=new BufferedReader(new InputStreamReader(process.getErrorStream())); } catch (Exception ioe) { System.out.println("IO Exception-> " + ioe); } } public void execution_command() { if(check==2) { try { boolean flag=thread.isAlive(); if(flag==true) thread.stop(); Thread.sleep(30); thread = new MyReader(br,tbOutput,err,check); thread.start(); }catch(Exception ex){ JOptionPane.showMessageDialog(null, ex.getMessage()+"1"); } } else { try { Thread.sleep(30); thread = new MyReader(br,tbOutput,err,check); thread.start(); check=2; }catch(Exception ex){ JOptionPane.showMessageDialog(null, ex.getMessage()+"1"); } } } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: command=tfCmd.getText().toString().trim(); pw.println(command); execution_command(); } when i enter some command in textfield and press execute button, nothing displayed on my output textarea, how i can stop shellexecution and can redirect Input and output?

    Read the article

  • Exception calling remote SOAP call from thread

    - by Duncan
    This is an extension / next step of this question I asked a few minutes ago. I've a Delphi application with a main form and a thread. Every X seconds the thread makes a web services request for a remote object. It then posts back to the main form which handles updating the UI with the new information. I was previously using a TTimer object in my thread, and when the TTimer callback function ran, it ran in the context of the main thread (but the remote web services request did work). This rather defeated the purpose of the separate thread, and so I now have a simple loop and sleep routine in my thread's Execute function. The problem is, an exception is thrown when returning from GetIMySOAPService(). procedure TPollingThread.Execute; var SystemStatus : TCWRSystemStatus; begin while not Terminated do begin sleep(5000); try SystemStatus := GetIMySOAPService().GetSystemStatus; PostMessage( ParentHandle, Integer(apiSystemStatus), Integer(SystemStatus), 0 ); SystemStatus.DataContext := nil; LParam(SystemStatus) := 0; except end; end; end; Can anyone advise as to why this exception is being thrown when calling this function from the thread? I'm sure I'm overlooking something fundamental and simple. Thanks, Duncan

    Read the article

  • twython search api rate limit: Header information will not be updated

    - by user2715478
    I want to handle the Search-API rate limit of 180 requests / 15 minutes. The first solution I came up with was to check the remaining requests in the header and wait 900 seconds. See the following snippet: results = search_interface.cursor(search_interface.search, q=k, lang=lang, result_type=result_mode) while True: try: tweet = next(results) if limit_reached(search_interface): sleep(900) self.writer(tweet) def limit_reached(search_interface): remaining_rate = int(search_interface.get_lastfunction_header('X-Rate-Limit-Remaining')) return remaining_rate <= 2 But it seems, that the header information are not reseted to 180 after it reached the two remaining requests. The second solution I came up with was to handle the twython exception for rate limitation and wait the remaining amount of time: results = search_interface.cursor(search_interface.search, q=k, lang=lang, result_type=result_mode) while True: try: tweet = next(results) self.writer(tweet) except TwythonError as inst: logger.error(inst.msg) wait_for_reset(search_interface) continue except StopIteration: break def wait_for_reset(search_interface): reset_timestamp = int(search_interface.get_lastfunction_header('X-Rate-Limit-Reset')) now_timestamp = datetime.now().timestamp() seconds_offset = 10 t = reset_timestamp - now_timestamp + seconds_offset logger.info('Waiting {0} seconds for Twitter rate limit reset.'.format(t)) sleep(t) But with this solution I receive this message INFO: Resetting dropped connection: api.twitter.com" and the loop will not continue with the last element of the generator. Have somebody faced the same problems? Regards.

    Read the article

  • InvalidOperationException when executing SqlCommand with transaction

    - by Serhat Özgel
    I have this code, running parallel in two separate threads. It works fine for a few times, but at some random point it throws InvalidOperationException: The transaction is either not associated with the current connection or has been completed. At the point of exception, I am looking inside the transaction with visual studio and verify its connection is set normally. Also command.Transaction._internalTransaction. _transactionState is set to Active and IsZombied property is set to false. This is a test application and I am using Thread.Sleep for creating longer transactions and causing overlaps. Why may the exception being thrown and what can I do about it? IDbCommand command = new SqlCommand("Select * From INFO"); IDbConnection connection = new SqlConnection(connectionString); command.Connection = connection; IDbTransaction transaction = null; try { connection.Open(); transaction = connection.BeginTransaction(); command.Transaction = transaction; command.ExecuteNonQuery(); // Sometimes throws exception Thread.Sleep(forawhile); // For overlapping transactions running in parallel transaction.Commit(); } catch (ApplicationException exception) { if (transaction != null) { transaction.Rollback(); } } finally { connection.Close(); }

    Read the article

  • how to restart a Thread?

    - by wizztjh
    It is a RMI Server object , so many sethumanActivity() might be run , how do i make sure the previous changeToFalse thread will be stop or halt before the new changeToFalse run? t. interrupt ? Basically when sethumanActivity() is invoke , the humanActivity will be set to true , but a thread will be run to set it back to false. But I am thinking for how to disable or kill the thread when another sethumanActivity() invoked? public class VitaminDEngine implements VitaminD { public boolean humanActivity = false; changeToFalse cf = new changeToFalse(); Thread t = new Thread(cf); private class changeToFalse implements Runnable{ @Override public void run() { try { Thread.sleep(4000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } humanActivity = false; } } @Override public void sethumanActivity() throws RemoteException { // TODO Auto-generated method stub humanActivity = true; t.start(); } public boolean gethumanActivity() throws RemoteException { // TODO Auto-generated method stub return humanActivity; } } Edited after the help of SOer package smartOfficeJava; import java.rmi.RemoteException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class VitaminDEngine implements VitaminD { public volatile boolean humanActivity = false; changeToFalse cf = new changeToFalse(); ExecutorService service = Executors.newSingleThreadExecutor(); private class changeToFalse implements Runnable{ @Override public void run() { try { Thread.sleep(4000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } humanActivity = false; } } @Override public synchronized void sethumanActivity() throws RemoteException { humanActivity = true; service.submit(cf); } public synchronized boolean gethumanActivity() throws RemoteException { return humanActivity; } }

    Read the article

  • Why doesn't Perl's Try::Tiny's try/catch give me the same results as eval?

    - by sid_com
    Why doesn't the subroutine with try/catch give me the same results as the eval-version does? #!/usr/bin/env perl use warnings; use strict; use 5.012; use Try::Tiny; sub shell_command_1 { my $command = shift; my $timeout_alarm = shift; my @array; eval { local $SIG{ALRM} = sub { die "timeout '$command'\n" }; alarm $timeout_alarm; @array = qx( $command ); alarm 0; }; die $@ if $@ && $@ ne "timeout '$command'\n"; warn $@ if $@ && $@ eq "timeout '$command'\n"; return @array; } shell_command_1( 'sleep 4', 3 ); say "Test_1"; sub shell_command_2 { my $command = shift; my $timeout_alarm = shift; my @array; try { local $SIG{ALRM} = sub { die "timeout '$command'\n" }; alarm $timeout_alarm; @array = qx( $command ); alarm 0; } catch { die $_ if $_ ne "timeout '$command'\n"; warn $_ if $_ eq "timeout '$command'\n"; } return @array; } shell_command_2( 'sleep 4', 3 ); say "Test_2"

    Read the article

  • can i know the Thread runnable class attributes in java?

    - by dori naji
    probability this question have been asked before but i cant find anything in my searching mechanism. I am trying to create a multiple threads, in an array list but i want to retrieve them from an arraylist and filter them by the attribute of w1 i used in my code. any ideas ? w1 = new FirstWorker(ProductsList, OrdersList, s); FirstWorkerThread = new Thread(w1); ThreadArrayList.add(FirstWorkerThread); //I know i cant do the code below but i want to do that how ? for(Thread x : ThreadArrayList){ x.ProductsList } this is FirstWorker class import java.lang.String; import java.util.HashMap; /* * To change this template, choose Tools | Templates and open the template in * the editor. */ /** * * @author Dimitris */ public class FirstWorker extends Thread implements Runnable { private OrderList orderlist; private ProductList productlist; private String Worker; boolean Stop; private int speed = 1000; public FirstWorker(ProductList productlist, OrderList orderlist, String Worker) { this.productlist = productlist; this.orderlist = orderlist; this.Worker = Worker; this.Stop = true; } public void run() { if (Stop == true) { try { Thread.sleep(100); } catch (InterruptedException e) { } while (orderlist.returnLengthofOrder() != 0) { if (Thread.interrupted()) { System.out.println("I am in the thread inturrupt"); // We've been interrupted: no more crunching. return; } if (orderlist.getDone() == true) { } else if (orderlist.getDone() == false) { orderlist.setDoneTrue(); orderlist.Purchased(Worker); orderlist.setDoneFalse(); try { Thread.sleep(this.speed); } catch (InterruptedException e) { return; } } } } } public void setWork() { Stop = false; } public void setSpeed(int speed) { this.speed = speed; } }

    Read the article

  • How to avoid shell execution of a Process?

    - by adeel amin
    When I start a process like process = Runtime.getRuntime().exec("gnome-terminal");, it starts shell execution. I want to stop shell execution and want to redirect I/O from process, can anybody tell how I can do this? My code is: public void start_process() { try { process= Runtime.getRuntime().exec("gnome-terminal"); pw= new PrintWriter(process.getOutputStream(),true); br=new BufferedReader(new InputStreamReader(process.getInputStream())); err=new BufferedReader(new InputStreamReader(process.getErrorStream())); } catch (Exception ioe) { System.out.println("IO Exception-> " + ioe); } } public void execution_command() { if(check==2) { try { boolean flag=thread.isAlive(); if(flag==true) thread.stop(); Thread.sleep(30); thread = new MyReader(br,tbOutput,err,check); thread.start(); }catch(Exception ex){ JOptionPane.showMessageDialog(null, ex.getMessage()+"1"); } } else { try { Thread.sleep(30); thread = new MyReader(br,tbOutput,err,check); thread.start(); check=2; }catch(Exception ex){ JOptionPane.showMessageDialog(null, ex.getMessage()+"1"); } } } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: command=tfCmd.getText().toString().trim(); pw.println(command); execution_command(); } When I enter some command in textfield and press execute button, nothing is displayed on my output textarea, how I can stop shell execution and redirect input and output?

    Read the article

  • How to tell when a Socket has been disconnected

    - by BowserKingKoopa
    On the client side I need to know when/if my socket connection has been broken. However the Socket.Connected property always returns true, even after the server side has been disconnected and I've tried sending data through it. Can anyone help me figure out what's going on here. I need to know when a socket has been disconnected. Socket serverSocket = null; TcpListener listener = new TcpListener(1530); listener.Start(); listener.BeginAcceptSocket(new AsyncCallback(delegate(IAsyncResult result) { Debug.WriteLine("ACCEPTING SOCKET CONNECTION"); TcpListener currentListener = (TcpListener)result.AsyncState; serverSocket = currentListener.EndAcceptSocket(result); }), listener); Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Debug.WriteLine("client socket connected: " + clientSocket.Connected);//should be FALSE, and it is clientSocket.Connect("localhost", 1530); Debug.WriteLine("client socket connected: " + clientSocket.Connected);//should be TRUE, and it is Thread.Sleep(1000); serverSocket.Close();//closing the server socket here Thread.Sleep(1000); clientSocket.Send(new byte[0]);//sending data should cause the socket to update its Connected property. Debug.WriteLine("client socket connected: " + clientSocket.Connected);//should be FALSE, but its always TRUE

    Read the article

  • curl_multi_exec stops if one url is 404, how can I change that?

    - by Rob
    Currently, my cURL multi exec stops if one url it connects to doesn't work, so a few questions: 1: Why does it stop? That doesn't make sense to me. 2: How can I make it continue? EDIT: Here is my code: $SQL = mysql_query("SELECT url FROM shells") ; $mh = curl_multi_init(); $handles = array(); while($resultSet = mysql_fetch_array($SQL)){ //load the urls and send GET data $ch = curl_init($resultSet['url'] . $fullcurl); //Only load it for two seconds (Long enough to send the data) curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_multi_add_handle($mh, $ch); $handles[] = $ch; } // Create a status variable so we know when exec is done. $running = null; //execute the handles do { // Call exec. This call is non-blocking, meaning it works in the background. curl_multi_exec($mh,$running); // Sleep while it's executing. You could do other work here, if you have any. sleep(2); // Keep going until it's done. } while ($running > 0); // For loop to remove (close) the regular handles. foreach($handles as $ch) { // Remove the current array handle. curl_multi_remove_handle($mh, $ch); } // Close the multi handle curl_multi_close($mh);

    Read the article

  • Inject runtime exception to pthread sometime fails. How to fix that?

    - by lionbest
    I try to inject the exception to thread using signals, but some times the exception is not get caught. For example the following code: void _sigthrow(int sig) { throw runtime_error(strsignal(sig)); } struct sigaction sigthrow = {{&_sigthrow}}; void* thread1(void*) { sigaction(SIGINT,&sigthrow,NULL); try { while(1) usleep(1); } catch(exception &e) { cerr << "Thread1 catched " << e.what() << endl; } }; void* thread2(void*) { sigaction(SIGINT,&sigthrow,NULL); try { while(1); } catch(exception &e) { cerr << "Thread2 catched " << e.what() << endl; //never goes here } }; If I try to execute like: int main() { pthread_t p1,p2; pthread_create( &p1, NULL, &thread1, NULL ); pthread_create( &p2, NULL, &thread2, NULL ); sleep(1); pthread_kill( p1, SIGINT); pthread_kill( p2, SIGINT); sleep(1); return EXIT_SUCCESS; } I get the following output: Thread1 catched Interrupt terminate called after throwing an instance of 'std::runtime_error' what(): Interrupt Aborted How can I make second threat catch exception? Is there better idea about injecting exceptions?

    Read the article

  • Multi threading in WCF RIA Services

    - by synergetic
    I use WCF RIA Services to update customer database. In domain service: public void UpdateCustomer(Customer customer) { this.ObjectContext.Customers.AttachAsModified(customer); syncCustomer(customer); } After update, a database trigger launches and depending on the columns updated it may insert a new record in CustomerChange table. syncCustomer(customer) method is executed to check for a new record in the CustomerChange table and if found it will create a text file which contains customer information and forwards that file to external system for import. Now this synchronization may take a time so I wanted to execute it in different thread. So: private void syncCustomer(Customer customer) { this.ObjectContext.SaveChanges(); new Thread(() => syncCustomerInfo(customer.CustomerID)) { IsBackground = true }.Start(); } private void syncCustomerInfo(int customerID) { //Thread.Sleep(2000); //does real job here ... ... } The problem is in most cases syncCustomerInfo method cannot find any new CustomerChange record even if it was definitely there. If I force thread sleep then it finds a new record. I also looked Entity Framework events but the only event provided by object context is SavingChanges which occur before changes are saved. Please suggest me what else to try.

    Read the article

  • Producer consumer with qualifications

    - by tgguy
    I am new to clojure and am trying to understand how to properly use its concurrency features, so any critique/suggestions is appreciated. So I am trying to write a small test program in clojure that works as follows: there 5 producers and 2 consumers a producer waits for a random time and then pushes a number onto a shared queue. a consumer should pull a number off the queue as soon as the queue is nonempty and then sleep for a short time to simulate doing work the consumers should block when the queue is empty producers should block when the queue has more than 4 items in it to prevent it from growing huge Here is my plan for each step above: the producers and consumers will be agents that don't really care for their state (just nil values or something); i just use the agents to send-off a "consumer" or "producer" function to do at some time. Then the shared queue will be (def queue (ref [])). Perhaps this should be an atom though? in the "producer" agent function, simply (Thread/sleep (rand-int 1000)) and then (dosync (alter queue conj (rand-int 100))) to push onto the queue. I am thinking to make the consumer agents watch the queue for changes with add-watcher. Not sure about this though..it will wake up the consumers on any change, even if the change came from a consumer pulling something off (possibly making it empty) . Perhaps checking for this in the watcher function is sufficient. Another problem I see is that if all consumers are busy, then what happens when a producer adds something new to the queue? Does the watched event get queued up on some consumer agent or does it disappear? see above I really don't know how to do this. I heard that clojure's seque may be useful, but I couldn't find enough doc on how to use it and my initial testing didn't seem to work (sorry don't have the code on me anymore)

    Read the article

  • Try::Tiny-Question

    - by sid_com
    Why doesn't the subroutine with try/catch give me the same results as the eval-version does. #!/usr/bin/env perl use warnings; use strict; use 5.012; use Try::Tiny; sub shell_command_1 { my $command = shift; my $timeout_alarm = shift; my @array; eval { local $SIG{ALRM} = sub { die "timeout '$command'\n" }; alarm $timeout_alarm; @array = qx( $command ); alarm 0; }; die $@ if $@ && $@ ne "timeout '$command'\n"; warn $@ if $@ && $@ eq "timeout '$command'\n"; return @array; } shell_command_1( 'sleep 4', 3 ); say "Test_1"; sub shell_command_2 { my $command = shift; my $timeout_alarm = shift; my @array; try { local $SIG{ALRM} = sub { die "timeout '$command'\n" }; alarm $timeout_alarm; @array = qx( $command ); alarm 0; } catch { die $_ if $_ ne "timeout '$command'\n"; warn $_ if $_ eq "timeout '$command'\n"; } return @array; } shell_command_2( 'sleep 4', 3 ); say "Test_2"

    Read the article

  • Can I prevent a Linux user space pthread yielding in critical code?

    - by KermitG
    I am working on an user space app for an embedded Linux project using the 2.6.24.3 kernel. My app passes data between two file nodes by creating 2 pthreads that each sleep until a asynchronous IO operation completes at which point it wakes and runs a completion handler. The completion handlers need to keep track of how many transfers are pending and maintain a handful of linked lists that one thread will add to and the other will remove. // sleep here until events arrive or time out expires for(;;) { no_of_events = io_getevents(ctx, 1, num_events, events, &timeout); // Process each aio event that has completed or thrown an error for (i=0; i<no_of_events; i++) { // Get pointer to completion handler io_complete = (io_callback_t) events[i].data; // Get pointer to data object iocb = (struct iocb *) events[i].obj; // Call completion handler and pass it the data object io_complete(ctx, iocb, events[i].res, events[i].res2); } } My question is this... Is there a simple way I can prevent the currently active thread from yielding whilst it runs the completion handler rather than going down the mutex/spin lock route? Or failing that can Linux be configured to prevent yielding a pthread when a mutex/spin lock is held?

    Read the article

  • How to parallelize this groovy code?

    - by lucas
    I'm trying to write a reusable component in Groovy to easily shoot off emails from some of our Java applications. I would like to pass it a List, where Email is just a POJO(POGO?) with some email info. I'd like it to be multithreaded, at least running all the email logic in a second thread, or make one thread per email. I am really foggy on multithreading in Java so that probably doesn't help! I've attempted a few different ways, but here is what I have right now: void sendEmails(List<Email> emails) { def threads = [] def sendEm = emails.each{ email -> def th = new Thread({ Random rand = new Random() def wait = (long)(rand.nextDouble() * 1000) println "in closure" this.sleep wait sendEmail(email) }) println "putting thread in list" threads << th } threads.each { it.run() } threads.each { it.join() } } I was hoping the sleep would randomly slow some threads down so the console output wouldn't be sequential. Instead, I see this: putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list putting thread in list in closure sending email1 in closure sending email2 in closure sending email3 in closure sending email4 in closure sending email5 in closure sending email6 in closure sending email7 in closure sending email8 in closure sending email9 in closure sending email10 sendEmail basically does what you'd expect, including the println statement, and the client that calls this follows, void doSomething() { Mailman emailer = MailmanFactory.getExchangeEmailer() def to = ["one","two"] def from = "noreply" def li = [] def email (1..10).each { email = new Email(to,null,from,"email"+it,"hello") li << email } emailer.sendEmails li }

    Read the article

< Previous Page | 28 29 30 31 32 33 34 35 36 37 38 39  | Next Page >