Signal in LINUX

Hi friends,

Currently, I'm working in wake-up issue in my project. I wanna inform android when my host OS windows wakes up. My project leader gave me an idea to send a signal from windows to android in the shell and use that signal to wake android when windows wakes up, like in exam days I keep alarm by 4am, my bad wakes up and give me a kick ;). But I'm zero at LINUX signal concept, as usual i studied it. Now, I'm typing here for my future ref. and other beginner's use.

SIGNAL IN LINUX

Now, we use CTRL + C to terminate something in LINUX. But, we don't wanna let someone to terminate our code with CTRL + C. So, what we have to do now. We have to monitor the user input and we should not let the system to perform any operation when user gives CTRL +C.

But, Instead what we can do in LINUX is, CTRL + C will generate a signal SIGINT in LINUX, so we can register a function to this signal in our code. So that when we user press CTRL + C, it will call our function, so our code won't be terminated.

What is signal in LINUX ? 
 LINUX has a set of signals. One nice example is, kill -9 PID, which we use to kill a process. Here, we are sending KILL signal to a process. Similarly, few other signals are available in LINUX. (SRY, i don't know to explain it, pls ask prof.google :( )

How can we register a function to a signal ?
here is the syntax,

signal(SIGINT, sig_handler)
SIGINT - signal generated on pressing CTRL + C. It can be any LINUX signal.
sig_handler - our function, which will be executed on receiving SIGINT signal.

What should be the sig_handler signature? 
here it is,
void sig_handler(int signo) {}
signo - signal number crossponding to the register signal.
Inside the function, we can write our own story.

Ok, How the final code will be? 
here is the simple one,
#include <stdio.h>
#include
<signal.h>
#include <unistd.h>

void sig_handler(int signo)
{
  if (signo == SIGINT)
    printf("received SIGINT\n");
}

int main(void)
{
  if (signal(SIGINT, sig_handler) == SIG_ERR)
  printf("\ncan't catch SIGINT\n");
  // A long long wait so that we can easily issue a signal to this process
  while(1)
    sleep(1);
  return 0;
}

Now, run the code and press CTRL + C. It will print "^Creceived SIGINT".

But, LINUX has alot of signals, is it possible to do for all signal of LINUX?
 Expect SIGKILL and SIGSTOP, we can use any signal in the place of SIGINT. So, change signal you would like register, change the body of sig_handler function as you like. Your coding will be done.

In my case, I have to generate a signal on my own... I choose to send user signal(SIGUSR1)...
So, the code will be?
here it is,

#include <stdio.h>
#include
<signal.h>
#include <unistd.h>

void sig_handler(int signo)
{
  if (signo == SIGUSR1)
    printf("received SIGUSR1\n");
}

int main(void)
{
  if (signal(SIGUSR1, sig_handler) == SIG_ERR)
  printf("\ncan't catch SIGUSR1\n");
  // A long long wait so that we can easily issue a signal to this process
  while(1)
    sleep(1);
  return 0;
}

Thats all, compile and run it :)... But how to send user signal? The following line will do that...
KILL -USR1 PID
 Got the signal!!!....

Android Input Device Events

Hi friends,

I have got task dealing with touch monitor. I have to implement multitouch in our project. In the middle, I wanted to see input events. My teammate gave me the keyword to see the input event and to manually send input event to any devices. I would like to put it here. So, Me and You can refer, when we want it...

Android getevent and sendevent 

ya, as you guess...
  • getevent is to read the input event from the device(/dev/input/device-name) and
  • sendevent is to write the input event to the device(/dev/input/device_name) manually
Before, the getevent and sendevent... Lets have a brief look into the input event...
Input Event : Basically inputs are written has (sequence of ) events in the device(/dev/input/event(device) in case of Linux). All input events comprise of three values namely,
  • Type  : type of the event like Key, Sync, Misc, LED, etc.
  • Code  : value corresponding to the key, which is pressed.
  • Value : Zero for release and One for click/press, in case of key press and mouse click event. some running number in other case( I don't have too much knowledge in it).
With these 3, OS will understand the input given by us and perform the action to the corresponding input.
 
Example : when we press key 2 in the keyboard... event sequence will be like the below

In ubuntu,  (I wrote a c program to read the input even from device and the output is below)
Event: type 4 (Misc), code 4 (ScanCode), value 458783   [Conveying the event is scancode]
Event: type 1 (Key), code 3 (2), value 1                             [key 2 pressed]
Event: type 0 (Sync), code 0 (Sync), value 0                      [sync event]
Event: type 4 (Misc), code 4 (ScanCode), value 458783    [conveying the event is scancode]
Event: type 1 (Key), code 3 (2), value 0                             [key 2 release]
Event: type 0 (Sync), code 0 (Sync), value 0                      [sync event]

In andriod,
Event: type 1 (Key), code 3 (2), value 1                             [key 2 pressed]
Event: type 0 (Sync), code 0 (Sync), value 0                      [sync event]
Event: type 1 (Key), code 3 (2), value 0                             [key 2 release]
Event: type 0 (Sync), code 0 (Sync), value 0                      [sync event]

This is for pressing the key 2 once... This will be written into the device, OS will read it and perform the actions.

ok now...

getevent : will print the event written into the device.
syntax    : getevent device
example : getevent /dev/input/event0
output    :  In android, it didn't say the scancode... but all the inputs are handled as scancodes. output is,
0001 0003 00000001
0000 0000 00000000
0001 0003 00000000
0000 0000 00000000

sendevent : will allow us to give the input in the terminal.
syntax       : sendevent device type code value.
example    : for writing key 2 into the device.
shell@android:/ # sendevent dev/input/event0 0000 0000 00000000
shell@android:/ # sendevent dev/input/event0 0001 0003 00000001
shell@android:/ # sendevent dev/input/event0 0000 0000 00000000
shell@android:/ # sendevent dev/input/event0 0000 0000 00000000


P.S. : Remember the two points below,

  1.  Run it in the android shell.
  2.  Should have root permission.


Mission Venkatagiri: Conquering of old robber’s fort!!! - Trekking


Hi friends,

Do you want to run over the stones, jump through the bushes and thorns, jump over the rocks, climb the mountain and visit a fort built by robbers before centuries???... What you say, “yes” or “no”???

As you say yes, everyone will say yes… because everyone wants their life to be adventurous…

But no one will ask for such an adventure. But few are little different like me. I googled for it... I googled “trekking near Chennai”… I found “Chennai Trekking Club (CTC)”. Members of CTC are people, who want adventure, who like outdoor activities.  I registered in it. Every weekend; organizers in CTC will organize some events like trekking, cycling, running, plantation, etc. Any members of CTC can register and take part in it. Importantly, CTC is non-profitable organization.

So, what is there after registering…? Adventures!!!

I started my adventures with Venkatagiri hills in AP, India.

And here is the story of my first trek…

Mission Venkatagiri: Conquering of old robber’s fort!!!

The story of 19 CTCians…

If I just say “they went and conquered it”, then the story won’t be interesting… So, let’s make it interesting now… So, ready for the story… Ya, here it is…

On sep 7th 2012 Midnight, 19 trekkers under team Emperors went to capture the old robber’s fort at venkatagiri hill on three fighter planes namely, Safari-0001, Ikon and Indica started from Chennai Tidal park, CMBT and Guindy. 

But conquering a fort without some hurdles won’t be possible right???...  ya they started facing problems since they started. At first, the Flight safari-0001’s Head light didn’t work!!! But our pilot Bala managed to ride without headlight.

The next big hurdle aroused in few minute since they started the fighter planes. They faced heavy rain. So, they parked those fighters under a bridge to repack the goods safely and to share the loads properly in all there fighter plane to product it from rain… And they started the journey again, But…………

Second Fighter IKON’s viper went off!!!... So another pilot Raghu had to manage without viper in that heavy rain. So, he followed the safari-0001 slowly. Then and there, our co-pilot Arul went out through the windows and dried the water as a viper (:P) while flying high. 

Then two, three hours went peacefully. Even many went to sleep… Around 5 AM in the Saturday morning, our third fighter Indica hit the road side pavement and got a flat tire. So, five of our warriors tried repair it. So, they took the spare tire out and placed it near the back tire and removed the front tire which got flat.

Wait wait!!! Do you want some twist??? Ok!  Within removing the front tire, our five warriors missed (lost) the spare tire… Dear Readers, I’m not making this twist on my own in the story… really they missed it… Believe me Pls!!! But I seriously feel that those old robbers sent these hurdles… what do you think???... Ok ok , back to the story… So they waited till the dawn and searched for it, but in vain. Hard decision was made to leave warriors Amrita and Tirthank, they bid adieu to them and carried with our journey. (Journey would have been better with you two frnds… Sry… we too missed you in this trek)


Then the 7 seater fighter became 11 seater safari-0001 and 5 seater fighter IKON became 6-seater…

After an hour or two, they reached venkatagiri… Captain Bala and Ravi went to local police station to warn everyone not to help those robbers to escape before they capture their fort… 

Then they went near to the base of the hill and parked the fighter in the near field and started walking. Pilots early had a plan to land the fighter planes right in the peak, but robbers may escape on seeing the fighter planes. So, they parked in the base and started walking to the robber’s fort…

On the way to the fort, they took tasty poli for lunch!!! And then with captain bala as the lead and Ravi as the sweep, they entered old robber’s fort by 4pm in the evening… But L … There were no robbers… 

I think, somehow they got information that the CTCians are coming to capture the fort… They evacuated their fort…

But our commando Raja took the knife out of his bag to slice the heads of those robbers. So, how can he keep the knife back into the bag without slicing something??? So, he sliced the heads of carrot, potatoes, tomatoes, onions… and made an awesome biriyani!!! With that biriyani our 17 warriors went to sleep… 

Next day beings with the temperature less than 16 degree and wind with the speed around 100km/hr… Since it was like, fan was running at full speed and AC was at 16 degree… our 17 warriors slept tight inside the blanket and tent. But, our pilot woke up all of them with a three letter word… any guess, what that word is???...No! He just said “TEA!!!”… With that everyone woke up to drink tea. But our pilot lied to wake up all, there were no tea!! …

Then warrior explored the fort and captured it in their memories and cams!!! Then our Bala, Ravi and Arul made wonderful tea and breakfast. Then they started home from the peak… 

Interesting, on the way back they saw 5 local guys and 2 outsiders climbing up… Our Ravi, Raja and few helped the local guys with water… Then they had rusk for lunch and reached back the base…

But they lost their way from the base to village. So, they explored the base and found our way back to village. 

Those nice villagers thought that our bala & ravi with their team, conquered and defeated those robbers. So, they helped the team to take bath at their pump. Poor villagers, they didn’t know that our     team didn’t even see a single robber there.
Then they loaded back in to the flights. But our pilot had parked the fighter safari safely in a pit. So, they struggled and with the help of the villagers, they lifted the fighter back from the pit. 

Then they came to know that local guys, who were all helped by our caption Ravi and Raja are robbers. They robbed the 2 outsiders, who were climbing up when our CTCian’s climbing down. And one of the Warriors Murali captured those robbers in his cam. But, they knew it only after reaching back Chennai. So, they were not able to help them at that time.

Then, our 17 trekkers left the ventakagiri and reached back Chennai on Sunday night.

Unforgettable Moments....
Tent...

Campfire...
Nature...
 Enjoyment...
Sunrise...
Climbing...
 Fort...

Me...

 From me

I enjoyed a lot... Though everyone was unknown to me until Friday midnight, I feel like, I spent two days with my cousins and close friends... These adventurous trips are dreams for me, since my childhood... "Superb Place, Awesome people, fabulous trip, a winning team.",  what else is needed for an adventurous trip...since we loaded bags in the car near the tidal park, everything was adventurous until we unloaded the bag from car back in CMBT...  Unforgettable weekend and my first trekking... Thanks all...It was really awesome… Looking forward for many more such an adventures treks!


By one among those 17,
ALAGAPPAN…

Android Notification ++

Hi friend,

Today, I was working in creating the Notification. I have to notify, when back button is pressed from my android app. As usual I went through the android developer site and studied how to do notify in the notification bar. But I had a small problem in it, which you can also get, when you work in Android Notification. So I planned to share it here.

Android Notification ++

Creating Notification is very simple. Just read it in android developer portal, probably you have to end with the following lines of code to create notification.

/Overriding the Back Button press event /
@Override
    public void onBackPressed() {
    // do something on back.

/* Get a reference to the NotificationManager */
    NotificationManager notificationManager = (NotificationManager)
                getSystemService(NOTIFICATION_SERVICE);

/* Instantiate the Notification */
    Notification notification = new Notification(R.drawable.icon,
            "A new notification", System.currentTimeMillis());

/* Hide the notification after its selected */
    notification.flags |= Notification.FLAG_AUTO_CANCEL;


/*  Creating the intent to an activity, which has to be called and setting it to notification */
    Intent intent = new Intent(this, ActivityName.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
    notification.setLatestEventInfo(this, "This is the title",
            "This is the text", activity);

/*Pass the Notification to the NotificationManager */   
    notification.number += 1;
    notificationManager.notify(0, notification);
    }

Sending the activity to background

But above lines of code will not send the activity to the background. So you will see the notification but the activity will be open. So you have to add the following line to send the activity to the background.

moveTaskToBack (true);

Bringing the activity to front


Once the notification is clicked, the intent will be created newly (note that the activity will be created newly). Older activity will be running in the back of the newly created activity. But most of the case we don't need it. We will need to open the activity that we sent to the background. The following line will do that magic for us.

intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

NOW

Creating the notification and sending the task to the back and on clicking the notification bringing the same old activity (or task) to the front is done by the following lines of code.

 @Override
    public void onBackPressed() {
        // do something on back.
        moveTaskToBack (true);
        NotificationManager notificationManager = (NotificationManager)
                getSystemService(NOTIFICATION_SERVICE);
    Notification notification = new Notification(R.drawable.ic_launcher,
            "A new notification", System.currentTimeMillis());
    // Hide the notification after its selected
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    Intent intent = new Intent(this, Test.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
    notification.setLatestEventInfo(this, "This is the title",
            "This is the text", activity);
    notification.number += 1;
    notificationManager.notify(0, notification);
    }

 Thats All!!! enjoy!!! 

Don't want your android to sleep soon!!!


Hi friend,

I got another one interesting task in my project.  The task is by default the sleep time in Android ICS was 1 min, we want to set to 30 minutes as default.

If you check in Settings > display > sleep, it will display as 1 minute as default and there will not be any never option.

So now if we want to change the default sleep value while customizing the android, just follow the following steps…

Step 1: open the following xml file… android/frameworks/base/packages/SettingsProvider/res/values/defaults.xml.

Step 2: change the default sleep time value in the line,
<"integer name="def_screen_off_timeout">60000<"/integer">… I changed it to 1800000 (30 minutes)…
Now, if you check in Settings > display > sleep, it will display as 30 minutes as default…

And if you don’t want timeout, set it to ‘-1’ …
Now, if you check in Settings > display > sleep, it won’t show any time out value… :)


ANOTHER METHOD: Editing the sleep time in the Settings source…

Step 1: open the file, android/packages/apps/Settings/src/com/android/settings/DisplaySettings.java

Step 2: Add the line, “Settings.System.putInt(getContentResolver(), SCREEN_OFF_TIMEOUT, -1);” before the line “ final long currentTimeout = Settings.System.getLong(resolver, SCREEN_OFF_TIMEOUT,               FALLBACK_SCREEN_TIMEOUT_VALUE);”

Now, if you check in Settings > display > sleep, it won’t show any time out value… :)

DO REBUILD THE ANDROID AFTER THE CHANGES!!! DON’T FORGET!!!

Task Completed :) :) :)

Out of Memory - dalvikvm-heap error

Hi friend,

Recently in our project SystemUI was crashing, saying that “Unfortunately, SystemUI has stopped”. I was supposed to fix it, so went through logcat and for found error as follow…

D/dalvikvm( 2120): GC_FOR_ALLOC freed 10K, 7% free 14024K/14983K, paused 10ms
I/dalvikvm-heap( 2120): Forcing collection of SoftReferences for 1587212-byte allocation
D/dalvikvm( 2120): GC_BEFORE_OOM freed 14K, 7% free 14009K/14983K, paused 0ms
E/dalvikvm-heap( 2120): Out of memory on a 1587212-byte allocation.
I/dalvikvm( 2120): "main" prio=5 tid=1 RUNNABLE
………………………………………………………………………………………..……………………………………………..
D/AndroidRuntime( 2120): Shutting down VM
W/dalvikvm( 2120): threadid=1: thread exiting with uncaught exception (group=0xb598b180)
E/AndroidRuntime( 2120): FATAL EXCEPTION: main
E/AndroidRuntime( 2120): java.lang.OutOfMemoryError
…………………………………………………………………………………………………………………………………………
E/AndroidRuntime( 2120):        at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 1682):   Force finishing activity 

SOLUTION

The error is the default heap size was not enough, so we need to increase the heap size or decrease the data in the heap to overcome this problem. We planned to increase the heap size. So we mounted the system image and edited the build.prop file in it, and then the problem was solved.

The solution is to increase the dalvik heap size by entering the one line in the build.prop script inside the system folder.

Step 1: use a file explore and open the build.prop file inside the system folder.
Step 2: enter the dalvik.vm.heapsize=32m. (I needed 32 MB of heap, so I specified it as 32… you can modify it as per your need)
Step 3: Restart your android.
The problem solved :)

If you are working with android source code…if you are customizing the android… and you want to solve in the source code… follow the following steps…

Step 1: open the main.mk in the folder android/build/core.
Step 2: enter the line ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.heapsize=32m (I needed 32 MB of heap, so I specified it as 32… you can modify it as per your need) after the line ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.stack-trace-file=/data/anr/traces.txt.
Step 3: save it and rebuilt it… 

The problem solved :)

From that time, I’m following the same, whenever I get out of memory problem ;)

Lost your GRUB??? - Boot-Repair

Hi friends,

Lost your GRUB??? don't go to police!!! i will help you... ;)
 
Recently when we installed winXP for testing our project, in the system which has Ubuntu and Win7 already installed... on the Next day, when we are done with testing... I wanted my Ubuntu and win7 back for development work...but when I restarted the system, I found that the GRUB was removed... and it took me half a session to overcome this problem... here is the solution for it now…(Don’t expect something great from me now...half session to Google and find the tool!!!)...

Lost your GRUB??? Here is the solution!!!...

Boot-Repair

This a free tool, to restore the GRUB in your system. When you run this tool, you will get back your last GRUB back, but the OS you installed and all the modification you have made in the system after losing the GRUB will be lost. In my case, I lost win XP... but I got back my Ubuntu and win7...
So here are the steps I followed,

 STEP 1: start the system with live USB or live CD... and get into Try Ubuntu mode... 
 STEP 2: open the terminal in the Ubuntu...
 STEP 3: run
sudo add-apt-repository ppa:yannubuntu/boot-repair && sudo apt-get update
sudo apt-get install -y boot-repair && boot-repair
STEP 4: reboot the system...

Thats all, now you can see your GRUB!!!...

For more information about BOOT-REPAIR, click here

But the correct method is by doing something in GRUB… but I don’t have that much knowledge in it… so I used BOOT-REPAIR…


Newer Posts Older Posts Home

About Me

My photo
Hi everyone,myself Alagappan...electronic and communication engg. student... living in madurai... interested in everything... want to achieve something great in my lifetime...

Followers


Recent Comments