Question

How to Use _damonize system call in Linux

Asked by: tittu

The requirement i have a function to be called at intervals of 5 seconds , I have registered SIGALRM
signal for 5 seconds and waiting with while(1); in main How to avoid while(1); so that Process Status will be show as S and when the Function is executing it should turn to R

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-10-28 at 21:49:27ID24853646
Topics

Unix Systems Programming

,

Linux Programming

,

Fedora Linux

Participating Experts
4
Points
500
Comments
25

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Linux threads vs signal handler
    Hi, I have a program in which I'm spawning of 3 child processes. The main associates a signal handler (Sigterm and Sigint) and than spawns 3 threads. After this main calls pthread_join to wait for 3 child processes to get over. In the signal handler method, in case the sign...
  2. Signal
    Hi Experts, I am trying to run java app in windows and getting : Exception in thread "main" java.lang.IlligalArgumentException: Signal already used by VM: SIGINT at sun.misc.Signal.handle(Signal.java:166) at com.myclass.class1(some.java: 196) at com.myclass.class2...
  3. Help in SIGNALS
    Hi there I am currently having problem with the following: * I am trying to write a program which will have two alarms, one will after ten seconds will write the message “time out”, and the other alarm will after 10 seconds will exit the problem is I need two handlers for thi...
  4. C: signal handling question
    Hello, using the following code I can happily send the process a SIGINT and it will prompt if I would like to continue etc... however, the second time around I have to press Ctrl-C twice before it enters the signal handler again and then it doesn't wait for my input from stdi...
  5. C Signal Handling Issue
    I have a signal handler that I initialize at the beginning of my main loop. The first time a SIGSEGV is called, the signal handler tries to run the main loop again. It then sets a flag. If this flag is true the next time the signal handler is called, the program attempts to c...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: natokaPosted on 2009-10-29 at 03:30:02ID: 25692095

I can only understand that you want to call a function every 5 seconds.
Please provide more information.

 

by: tittuPosted on 2009-10-29 at 06:33:19ID: 25693423

yes but not in while(1) loop

 

by: natokaPosted on 2009-10-30 at 03:18:14ID: 25701530

So where exactly is your problem with this?

 

by: tittuPosted on 2009-10-30 at 05:05:05ID: 25702071

i need to write a program to call a function for every 5 seconds and should not wait in while(1)
loop

 

by: mrjoltcolaPosted on 2009-10-30 at 18:33:44ID: 25707958

Use sleep()

 

by: tittuPosted on 2009-10-31 at 03:35:44ID: 25709132

The Question is very simple how to avoid while(1) in code which is using SIGALRM
like this

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

int wakeUp() {

        printf("Wake up \n");
        signal(SIGALRM,wakeUp);
        alarm(1);

}

int main() {
        signal(SIGALRM,wakeUp);
        alarm(1);
        while(1);
        return(0);

}

How to avoid while(1) in the above

 

by: franceskinmPosted on 2009-11-02 at 04:43:13ID: 25718824

I attached a code snippet for implementation kernel threads functions (you'll see that daemonize is used inside).

This an example of independent thread that will print something every 5 seconds and exit after repeating it 100 times:

static void my_thread(kthread_t *kthread)
{
  int f;
  init_kthread(kthread, "my_thread");

  for (f=0; f<10; f++)
  {
    printk(KERN_INFO "Hello world");
    sleep(5);
  }

  exit_kthread(kthread);
}


kthread_t my_thread_handle;
start_kthread(my_thread, &my_thread_handle);

/* kthread.h */
#ifndef _KTHREAD_H
#define _KTHREAD_H
#include <linux/config.h>
#include <linux/version.h> 
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/wait.h> 
#include <asm/unistd.h>
#include <asm/semaphore.h> 
/* a structure to store all information we need for our thread */
typedef struct kthread_struct
{
  /* private data */ 
  /* Linux task structure of thread */
  struct task_struct *thread;
  /* function to be started as thread */
  void (*function) (struct kthread_struct *kthread);
  /* semaphore needed on start and creation of thread. */
  struct semaphore startstop_sem; 
  /* public data */ 
  /* queue thread is waiting on. Gets initialized by
     init_kthread, can be used by thread itself.
  */
  wait_queue_head_t queue;
  /* flag to tell thread whether to die or not.
     When the thread receives a signal, it must check
     the value of terminate and call exit_kthread and terminate
     if set.
  */
  int terminate;
  /* additional data to pass to kernel thread */
  void *arg;
} kthread_t; 
/* prototypes */ 
/* start new kthread (called by creator) */
void start_kthread(void (*func)(kthread_t *), kthread_t *kthread); 
/* stop a running thread (called by "killer") */
void stop_kthread(kthread_t *kthread); 
/* setup thread environment (called by new thread) */
void init_kthread(kthread_t *kthread, char *name); 
/* cleanup thread environment (called by thread upon receiving termination signal) */
void exit_kthread(kthread_t *kthread); 
#endif 
/*==========================================================================*/
/* kthread.c */
#include <linux/config.h>
#include <linux/version.h> 
#if defined(MODVERSIONS)
#include <linux/modversions.h>
#endif
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/wait.h>
#include <linux/signal.h>
#include <linux/smp_lock.h> 
#include <asm/semaphore.h> 
#include "kthread.h" 
/* create a new kernel thread. Called by the creator. */
void start_kthread(void (*func)(kthread_t *), kthread_t *kthread)
{
  /* initialize the semaphore:
     we start with the semaphore locked. The new kernel
     thread will setup its stuff and unlock it. This
     control flow (the one that creates the thread) blocks
     in the down operation below until the thread has reached
     the up() operation.
  */
  init_MUTEX_LOCKED(&kthread->startstop_sem); 
  /* store the function to be executed in the data passed to the launcher */
  kthread->function = func;
        
  kernel_thread((int (*)(void *))kthread->function, (void *) kthread, 0); 
  /* wait till it has reached the setup_thread routine */
  down(&kthread->startstop_sem);
} 
/* stop a kernel thread. Called by the removing instance */
void stop_kthread(kthread_t *kthread)
{
  if (kthread->thread == NULL)
  {
/*    printk(KERN_DEBUG "KTHREAD: stop_kthread: killing non existing thread!\n");*/
    return;
  } 
  /* this function needs to be protected with the big
	   kernel lock (lock_kernel()). The lock must be
     grabbed before changing the terminate
	   flag and released after the down() call. */
  lock_kernel();
        
  /* initialize the semaphore. We lock it here, the
     leave_thread call of the thread to be terminated
     will unlock it. As soon as we see the semaphore
     unlocked, we know that the thread has exited.
	*/
  init_MUTEX_LOCKED(&kthread->startstop_sem); 
  /* We need to do a memory barrier here to be sure that
     the flags are visible on all CPUs. 
  */
  mb(); 
  /* set flag to request thread termination */
  kthread->terminate = 1; 
  /* We need to do a memory barrier here to be sure that
     the flags are visible on all CPUs. 
  */
  mb();
  kill_proc(kthread->thread->pid, SIGKILL, 1);
       
  /* block till thread terminated */
  down(&kthread->startstop_sem); 
  /* release the big kernel lock */
  unlock_kernel();
} 
/* initialize new created thread. Called by the new thread. */
void init_kthread(kthread_t *kthread, char *name)
{
  daemonize(name, 0);
  /* lock the kernel. A new kernel thread starts without
     the big kernel lock, regardless of the lock state
     of the creator (the lock level is *not* inheritated) */
  lock_kernel(); 
  /* fill in thread structure */
  kthread->thread = current; 
  /* set signal mask to what we want to respond */
  siginitsetinv(&current->blocked, sigmask(SIGKILL)|sigmask(SIGINT)|sigmask(SIGTERM)); 
  /* initialise wait queue */
  init_waitqueue_head(&kthread->queue); 
  /* initialise termination flag */
  kthread->terminate = 0; 
  /* set name of this process (max 15 chars + 0 !) */
  sprintf(current->comm, name);
        
  /* let others run */
  unlock_kernel(); 
  /* tell the creator that we are ready and let him continue */
  up(&kthread->startstop_sem); 
/*  printk(KERN_DEBUG "KTHREAD started thread: %s\n", name);*/
} 
/* cleanup of thread. Called by the exiting thread. */
void exit_kthread(kthread_t *kthread)
{
  /* we are terminating */ 
	/* lock the kernel, the exit will unlock it */
  lock_kernel();
  kthread->thread = NULL;
  mb(); 
  /* notify the stop_kthread() routine that we are terminating. */
	up(&kthread->startstop_sem);
	/* the kernel_thread that called clone() does a do_exit here. */ 
	/* there is no race here between execution of the "killer" and real termination
	   of the thread (race window between up and do_exit), since both the
	   thread and the "killer" function are running with the kernel lock held.
	   The kernel lock will be freed after the thread exited, so the code
	   is really not executed anymore as soon as the unload functions gets
	   the kernel lock back.
	   The init process may not have made the cleanup of the process here,
	   but the cleanup can be done safely with the module unloaded.
	*/
/*  printk(KERN_DEBUG "KTHREAD: ended thread %s\n", current->comm);*/
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:

Select allOpen in new window

 

by: natokaPosted on 2009-11-02 at 06:52:44ID: 25719844

you can replace the while(1) with for example reading some input like:

int help;
help = fgetc(stdin);

That would make the program wait until you press either enter or CTRL+D.

 

by: duncan_roePosted on 2009-11-02 at 17:16:57ID: 25725394

while(1); is a no-no. It will soak up all available CPU.
Since you are already using SIGALRM, you cannot do while(1) sleep(1); because sleep() also uses SIGALRM.
But you *can* use nanosleep(), because it doesn't use any signals. The SIGALRM will interrupt it, so you can nanosleep as long as you like. You still need the while(1), but only to restart nanosleep once per SIGALRM received.
It is good practice to do as little as possible in a signal handler. Reinstating the signal handler is fine: to avoid that necessity, you can use the more modern sigaction call. Otherwise, best practice is to set a flag for the main program to action, and return. Calling printf() in particular is not a good idea, since the signal you are handling might have interrupted another printf() if you see what I mean.

See next post for some ideas

 

by: duncan_roePosted on 2009-11-02 at 17:19:30ID: 25725406

"Otherwise, best practice is ..." should be "Either way, best practice is ..."

This is not the "next post" mentioned in the previous post, that post is still to come :)

 

by: duncan_roePosted on 2009-11-02 at 19:28:14ID: 25725847

It's always a good idea to compile with option "-Wall". Also I always use "-Wstrict-prototypes -Wmissing-prototypes", which has found a few problems for me in the past.

12:31:05$ gcc -Wall -g3 -ggdb ee52.c -o ee52
ee52.c: In function 'wakeUp':
ee52.c:10: warning: passing argument 2 of 'signal' from incompatible pointer type
ee52.c:11: warning: implicit declaration of function 'alarm'
ee52.c:13: warning: control reaches end of non-void function
ee52.c: In function 'main':
ee52.c:16: warning: passing argument 2 of 'signal' from incompatible pointer type

Ok they're just warnings, but a warning can indicate a program which will nor tun correctly. So let's fix them:-

ee52.c:10: warning: passing argument 2 of 'signal' from incompatible pointer type: from the man page, we see that the signal handler given to signal() should be a function returning void (i.e. not returning anything) and taking an integer argument. Make that change and try again:

4c4
< int wakeUp() {
---
> void wakeUp(int signum) {

12:43:12$ gcc -Wall -g3 -ggdb ee52.c -o ee52
ee52.c: In function 'wakeUp':
ee52.c:11: warning: implicit declaration of function 'alarm'

We are missing the header that describes the alarm() system call. From "man -s 2 alarm" we see that it is unistd.h, so insert it:

2a3
> #include <unistd.h>

12:50:39$ gcc -Wall -g3 -ggdb ee52.c -o ee52
12:50:44$

The warning-free program is the 1st listing below.

Humor an old man and let's fix -Wstrict-prototypes -Wmissing-prototypes:-

12:56:14$ gcc -Wall -g3 -ggdb ee52.c -o ee52 -Wstrict-prototypes -Wmissing-prototypes
ee52.c:9: warning: no previous prototype for 'wakeUp'
ee52.c:17: warning: function declaration isn't a prototype

One could fix "no previous prototype" by inserting the line:

void wakeUp(int signum);

as a prototype before the function declaration. But there's a quicker way (in terms of programmer's time) - just make it static. It is a style of programming that not everyone agrees with (to put all static declarations before the mainline thus avoiding the need for prototypes) but a common style nevertheless.:

< void wakeUp(int signum) {
---
> static void wakeUp(int signum) {

13:08:05$ gcc -Wall -g3 -ggdb ee52.c -o ee52 -Wstrict-prototypes -Wmissing-prototypes
ee52.c:17: warning: function declaration isn't a prototype

The "function declaration isn't a prototype" message appears because you declared main() with empty parentheses. Gcc can't be sure if that isn't an old-style function declaration (you don't want to know about those:) so raises a warning. You explicitly have to tell gcc that main() takes no arguments

17c17
< int main() {
---
> int main(void) {

13:14:54$ gcc -Wall -g3 -ggdb ee52.c -o ee52 -Wstrict-prototypes -Wmissing-prototypes
13:15:02$

Hope you're still reading - now to fix the program:

7a8,12
> #include <time.h>                  /* For nanosleep */

> #define WAIT_TIME 5

> static int flag = 0;               /* For the handler to set */
11d15
<     printf("Wake up \n");
13c17,18
<     alarm(1);
---
>     alarm(WAIT_TIME);
>     flag = 1;
17a23,27
>     
>     struct timespec req;           /* Requested wait time */
>     
>     req.tv_sec = 1;
>     req.tv_nsec = 500000000;
19,20c29,38
<     alarm(1);
<     while(1);
---
>     alarm(WAIT_TIME);
>     while(1)
>     {
>         nanosleep(&req, NULL);
>         if (flag)
>         {
>             flag = 0;
>             printf("Woken by alarm - do your processing here\n");
>         }
>     }

I changed back to 5 second alarm as you originally mentioned.
The nanosleep time is less than the alarm time just in case the alarm gets missed (most unlikely). You could have a nanosleep time of 100 seconds. Best not to make it an exact fraction of the alarm time - you could just possibly miss an alarm if it went off outside of nanosleep. Hence I set it at 1.5 secs.

If you can find the running program in "top", it certainly stays in the S state.

I really would caution against doing your processing in the signal handler even though in this simple example you might get away with it.

12:52:41$ cat ee52.c
/*
Warning-free with:
gcc -Wall -g3 -ggdb ee52.c -o ee52
*/
#include <stdio.h>
#include <signal.h>
#include <unistd.h> 
void wakeUp(int signum) { 
    printf("Wake up \n");
    signal(SIGALRM,wakeUp);
    alarm(1); 
} 
int main() {
    signal(SIGALRM,wakeUp);
    alarm(1);
    while(1);
    return(0); 
} 
================================================ 
13:15:02$ cat ee52.c
/*
Warning-free with:
gcc -Wall -g3 -ggdb ee52.c -o ee52 -Wstrict-prototypes -Wmissing-prototypes
*/
#include <stdio.h>
#include <signal.h>
#include <unistd.h> 
static void wakeUp(int signum) { 
    printf("Wake up \n");
    signal(SIGALRM,wakeUp);
    alarm(1); 
} 
int main(void) {
    signal(SIGALRM,wakeUp);
    alarm(1);
    while(1);
    return(0); 
} 
================================================ 
14:15:15$ cat ee52.c
/*
Warning-free with:
gcc -Wall -g3 -ggdb ee52.c -o ee52 -Wstrict-prototypes -Wmissing-prototypes
*/
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <time.h>                  /* For nanosleep */ 
#define WAIT_TIME 5 
static int flag = 0;               /* For the handler to set */ 
static void wakeUp(int signum) { 
    signal(SIGALRM,wakeUp);
    alarm(WAIT_TIME);
    flag = 1; 
} 
int main(void) {
    
    struct timespec req;           /* Requested wait time */
    
    req.tv_sec = 1;
    req.tv_nsec = 500000000;
    signal(SIGALRM,wakeUp);
    alarm(WAIT_TIME);
    while(1)
    {
        nanosleep(&req, NULL);
        if (flag)
        {
            flag = 0;
            printf("Woken by alarm - do your processing here\n");
        }
    }
    return(0); 
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:

Select allOpen in new window

 

by: tittuPosted on 2009-11-06 at 01:13:47ID: 25757688

thank you guys for the suggestions and when i tried with GMainloop using the glib library and avoided while(1); loop and now the Process status is always show as S sleep state.

but what is the trick of gmainloop

 

by: duncan_roePosted on 2009-11-06 at 01:58:33ID: 25757851

I think GMainloop  waits for X events. As such, it is likely doing (select or poll) or a blocking i/o. You could find out what exactly it is doing by using the strace command e.g.

strace -p $(pgrep YourApp)

where "YourApp" is the name of your program. strace won't tell you this, but GMainloop is probably in a while(1) loop or the equivalent. So you are simply (and unnecessarily) getting another package to do your dirty work for you.
In my last post, I think I forgot to mention that nanosleep() will get interrupted when the alarm goes off, so timing will be as accurate as alarm() is.

 

by: tittuPosted on 2009-11-09 at 00:04:04ID: 25774081

Thanks for the suggestions guys but how the
gmainloop in glib is able to do the trick without using while(1);

 

by: duncan_roePosted on 2009-11-09 at 00:46:51ID: 25774224

It probably does use while(1), it's just that it does something in the middle (such as a blocking i/o) so that very little CPU is used. A blocking i/o will be interrupted by receipt of a caught signal, just as nanosleep would be. You are wasting your time calling GMainloop.

 

by: tittuPosted on 2009-11-09 at 20:47:08ID: 25782485

you mean using  nanosleep(&req, NULL); is more efficient way than GMainLoop ?

 

by: duncan_roePosted on 2009-11-10 at 02:10:20ID: 25783914

Yes absolutely. Dragging in all the GMainLoop code just makes your program bigger for no good reason. Rather than sitting on a blocking i/o, it may be in poll() or select() but whatever it's doing it's doing you no good.

 

by: tittuPosted on 2009-11-10 at 03:34:35ID: 25784348

Last question how nanosleep() function in while(1) loop is managing  CPU state with
Suspend/Sleep Mode.

 

by: duncan_roePosted on 2009-11-10 at 11:40:38ID: 25788931

While in nanosleep(), the process is shown by top as sleeping. No CPU is being used. Is that what you were asking?

 

by: tittuPosted on 2009-11-10 at 21:45:23ID: 25792579

exactly how is this process shown in Sleep State ?

 

by: duncan_roePosted on 2009-11-11 at 03:36:29ID: 25794160

There's an S against it in top. (You can only see it in top by using -p {pid of program} unless you have so few processes that they all fit on your screen).
From man top:

       w: S  --  Process Status
          The status of the task which can be one of:
             'D' = uninterruptible sleep
             'R' = running
             'S' = sleeping
             'T' = traced or stopped
             'Z' = zombie

          Tasks shown as running should be more properly thought of as 'ready to run'  --  their task_struct is simply represented on the Linux run-queue.  Even without a true SMP machine, you may see numerous
          tasks in this state depending on top's delay interval and nice value.

 

by: tittuPosted on 2009-11-11 at 20:20:59ID: 25801479

I verified with ps -elf command the Process Status is always 'S' Sleeping State with while(1) nanosleep.  
My question is how is this process in sleep state and able to schedule timer function at intervals
when sigalrm is expired and the process never shown as R running state even though in while(1);

 

by: duncan_roePosted on 2009-11-12 at 01:53:01ID: 25802813

The process is in R state for such a short time that top never gets to display it. If you did something that took a few seconds of CPU to complete, then top would show it. See a little experiment of mine below

20:50:24$ cat ee53.c
/*
gcc -Wall -Wmissing-prototypes -Wstrict-prototypes -g3 -ggdb ee53.c -o ee53
*/
int main(void)
{
  int i;
  for (i=1; i;)
    i++;
  return 0;
}
20:50:42$ time ./ee53 
real    0m10.701s
user    0m10.701s
sys     0m0.000s
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:

Select allOpen in new window

 

by: duncan_roePosted on 2009-11-14 at 16:20:49ID: 25823053

Hey tittu - if you are happy with the answers you received then you should close & award points.

 

by: tittuPosted on 2009-11-18 at 08:09:19ID: 31647364

Agreed

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...