473,657 Members | 2,934 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sleep( ) misbehaving

I am trying to write a little program that goes to sleep for 5 seconds.
However, if the user presses Ctrl-C, it interrupts the sleep and prints the
unslept amount.

For example:

unix> ./sleeper
sleeping for 5 seconds
unslept amount is 2 (User hits Ctrl-C after 3 seconds)
unix>

What's wrong with the code below?
-------------------------------

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

unsigned int unslept;

void handler (int sig)
{
printf("unslept amount is %d",unslept);
exit(0);
}

int main()
{
signal(SIGINT,h andler);
printf("sleepin g for 5 seconds\n");
unslept = sleep(5);
return 0;
}
Dec 8 '05 #1
10 3526
syed wrote:
I am trying to write a little program that goes to sleep for 5 seconds.
However, if the user presses Ctrl-C, it interrupts the sleep and prints the
unslept amount.

<snip>
You're looking for comp.unix.progr ammer. sleep() is a nonstandard function.
Also see http://www.ungerhu.com/jxh/clc.welcome.txt.

S.
Dec 8 '05 #2
syed a écrit :
I am trying to write a little program that goes to sleep for 5 seconds.
However, if the user presses Ctrl-C, it interrupts the sleep and prints the
unslept amount.

For example:

unix> ./sleeper
sleeping for 5 seconds
unslept amount is 2 (User hits Ctrl-C after 3 seconds)
unix>

What's wrong with the code below?
-------------------------------

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

unsigned int unslept;

void handler (int sig)
{
printf("unslept amount is %d",unslept);
exit(0);
}

int main()
{
signal(SIGINT,h andler);
printf("sleepin g for 5 seconds\n");
unslept = sleep(5);
return 0;
}


After 3 seconds you sent the program a signal (SIGINT) with
the Ctrl+C keys. You got into your handler procedure
and exited.

What else do you want?

Signals are asynchronous in C.

Programs doing something can at any moment be redirected to a signal
handler.

This is normal behavior.

jacob
Dec 8 '05 #3
"jacob navia" <ja***@jacob.re mcomp.fr> wrote:
After 3 seconds you sent the program a signal (SIGINT) with
the Ctrl+C keys. You got into your handler procedure
and exited.

What else do you want?


I want it to print the unslept time correctly. My code always prints ZERO
for unslept time.

unix> ./sleeper
sleeping for 5 seconds
unslept amount is 0 (This line prints when user
hits Ctrl-C, unslept amount is always zero)
unix>

I want it to print the acutal time left to sleep. For example if the user
hits Ctrl-C after three seconds, then it should print 2 for unslept time:

unix> ./sleeper
sleeping for 5 seconds
unslept amount is 2 (User hits Ctrl-C after 3
seconds)
unix>

----
Thanks.
Syed
Dec 8 '05 #4

"jacob navia" <ja***@jacob.re mcomp.fr> wrote in message
news:43******** *************** @news.wanadoo.f r...
syed a écrit :
I am trying to write a little program that goes to sleep for 5 seconds.
However, if the user presses Ctrl-C, it interrupts the sleep and prints
the unslept amount.

For example:

unix> ./sleeper
sleeping for 5 seconds
unslept amount is 2 (User hits Ctrl-C after 3 seconds)
unix>

What's wrong with the code below?


unslept variable won't be set until AFTER the sleep() returns.
Move the printf() out of the signal handler (shouldn't do i/o in
there anyway) and place it after the call where it is set.
shitcan the exit() from your handler and just return sig;
That should do what you want.
Dec 8 '05 #5
syed wrote:
I want it to print the unslept time correctly. My code always prints ZERO
for unslept time.


that's because you never let sleep finish.

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

void handler (int sig)
{
}

int main()
{
unsigned int unslept;
signal(SIGINT,h andler);
printf("sleepin g for 5 seconds\n");
unslept = sleep(5);
if (unslept)
printf("time not slept %d\n" unslept);
return 0;
}

Dec 8 '05 #6
syed wrote:

"jacob navia" <ja***@jacob.re mcomp.fr> wrote:
After 3 seconds you sent the program a signal (SIGINT) with
the Ctrl+C keys. You got into your handler procedure
and exited.

What else do you want?


I want it to print the unslept time correctly. My code always prints ZERO
for unslept time.


Well, it would have been nice if you said so in the first place, rather
than showing a sample of the "correct" output.

[...]

As has been pointed out, sleep() is not standard C, so is off-topic here.
While the man page on _my_ Unix system says:

If the sleep() function returns due to the delivery of a signal,
the value returned will be the unslept amount in seconds.

there is nothing as far as C itself is concerned that says that this must
be the return value. Check the man pages for your particular system, and
if it says it should "work" as you expect, then you need to ask a group
that is appropriate for your system-specific question.

On the other hand, note that the signal handler will be called _before_
the interrupted sleep() call returns.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Dec 9 '05 #7
"syed" <su*******@gmai l.com> writes:
I am trying to write a little program that goes to sleep for 5 seconds.
However, if the user presses Ctrl-C, it interrupts the sleep and prints the
unslept amount.

For example:

unix> ./sleeper
sleeping for 5 seconds
unslept amount is 2 (User hits Ctrl-C after 3 seconds)
unix>

What's wrong with the code below?
-------------------------------

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

unsigned int unslept;

void handler (int sig)
{
printf("unslept amount is %d",unslept);
exit(0);
}

int main()
{
signal(SIGINT,h andler);
printf("sleepin g for 5 seconds\n");
unslept = sleep(5);
return 0;
}


sleep() is off-topic, but signals are part of the C standard.

Try this:

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

unsigned int unslept = 42;

void handler (int sig)
{
printf("unslept amount is %d\n",unslept);
exit(0);
}

int main()
{
signal(SIGINT,h andler);
printf("sleepin g for 5 seconds\n");
unslept = sleep(5);
return 0;
}

(I've added a newline to the message printed by handler(), and I've
initialized unslept to 42.)

If the call to sleep() is interrupted by a SIGINT, it never returns,
so the assignment "unslept = sleep(5);" is never executed. The
variable retains its previous value, which is 0 in your original
program, 42 in my version.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 9 '05 #8
Keith Thompson <ks***@mib.or g> writes:
[snip]
sleep() is off-topic, but signals are part of the C standard.

Try this:

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

unsigned int unslept = 42;

void handler (int sig)
{
printf("unslept amount is %d\n",unslept);
exit(0);
}

int main()
{
signal(SIGINT,h andler);
printf("sleepin g for 5 seconds\n");
unslept = sleep(5);
return 0;
}

(I've added a newline to the message printed by handler(), and I've
initialized unslept to 42.)

If the call to sleep() is interrupted by a SIGINT, it never returns,
so the assignment "unslept = sleep(5);" is never executed. The
variable retains its previous value, which is 0 in your original
program, 42 in my version.


One more thing: the reason sleep() never returns is that you do an
exit(0) in the signal handler. If you delete that line, you'll find
that the sleep() call does complete, and the variable unslept is set
to whatever value it returns.

What that value might be depends on what the sleep() function does,
something not covered by the C standard.

Also, you should use "%u", not "%d", to print an unsigned int value.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 9 '05 #9
In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.or g> wrote:
sleep() is off-topic, but signals are part of the C standard. Try this: #include <stdio.h>
#include <stdlib.h>
#include <signal.h> unsigned int unslept = 42; void handler (int sig)
{
printf("unslept amount is %d\n",unslept);
exit(0);
}


The C89 standard says that except for signals occuring from
abort() or raise(), you have UB if the signal handler calls
any library function other than signal() or refers to any static
variable that isn't volatile sig_atomic_t .

Your example code refers to a static variable that isn't sig_atomic_t
and calls two library functions other than signal...
--
"law -- it's a commodity"
-- Andrew Ryan (The Globe and Mail, 2005/11/26)
Dec 9 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
13973
by: Anks | last post by:
hi I am displaying a digital clock in an applet.I am using Thread.sleep (1000) for counting every second.This works fine some times but some times my clock just slows down or give an interrupted exception .I am not calling Thread.interrupt anywhere in my program. why is it happening? how to fix the problem? Anks
7
10257
by: Colin Brown | last post by:
Python 2.3.3 Under Windows NT: Negative Int or Real -> sleeps for a long time Under Linux: Returns IOError: Invalid argument I consider both of these unfriendly results and expected the preferable silent time.sleep(0) in much the same way that slicing a string beyond the ends returns an empty string. Colin Brown PyNZ
5
5534
by: Dave | last post by:
For the life of me, I thought there was a sleep() function in the Standard Library (or something similarly named), but I can't find it. Is it non-existent or, if not, what header is it in? Thanks! Dave
21
18710
by: Alo Sarv | last post by:
Hi From what I have understood from various posts in this newsgroup, writing event loops pretty much comes down to this: while (true) { handleEvents(); sleep(1); // or _sleep() or nanosleep(), depending on platform }
1
2154
by: u473 | last post by:
Running Totals by date misbehaving I applied to the letter the sample code given on http://support.microsoft.com/?kbid=290136 but it seems the running total breaks when the day number is less than the previous date Example using one Table (Access 2000):
8
2777
by: Cider123 | last post by:
I ran into a situation where my Window Service had to process 100,000+ files, when I first noticed I needed to tweak various routines. Everything runs fine, but here's what I ran into: In the routine that loops through the file buffer: for (int i=0;i < _Buffer.length; i++) { // Code here
17
6408
by: OlafMeding | last post by:
Below are 2 files that isolate the problem. Note, both programs hang (stop responding) with hyper-threading turned on (a BIOS setting), but work as expected with hyper-threading turned off. Note, the Windows task manager shows 2 CPUs on the Performance tab with hyper-threading is turned on. Both Python 2.3.5 and 2.4.3 (downloaded from python.org) have this problem. The operating system is MS Windows XP Professional.
1
2764
by: Matt Brown - identify | last post by:
Hello, I, as well as suspecting many others, am having an issue when I attempt to enter sleep mode in Vista. If any program is connected to the internet (AOL Instant Messenger for instance), and I go to enter Sleep mode; Vista will automatically leave Sleep mode immediately. I believe this is caused by the fact that Sleep attempts to disconnect AIM, then AIM attempts to reconnect; thrwarting Vista's attempt to
13
5820
by: Charles Zhang | last post by:
Sleep() function Sleep at lease 1 millisecond, there is a way to make a thread to sleep less than a millisecond? One way I know of is using performance counter which is not really sleep ( loop and check again and again and uses CPU time). Thanks Charles Zhang
0
8820
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8499
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8601
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7314
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1937
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1601
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.