C Programming: Understanding the `alarm()` Function 🎯

beginner
20 min

C Programming: Understanding the alarm() Function 🎯

Welcome to our comprehensive guide on the alarm() function in C programming! This tutorial is designed to help you understand the concept from scratch and by the end, you'll be able to use it confidently in your own projects.

What is the alarm() Function? 📝

The alarm() function is a part of the POSIX standard library and is used to set an alarm that generates a signal after a specified time. In C programming, it's particularly useful for scheduling tasks and managing time-sensitive operations.

Why use the alarm() Function? 💡

  • Scheduling periodic tasks: You can use alarm() to schedule periodic tasks that need to run after specific intervals.
  • Time management: alarm() can help manage the execution time of your programs by setting time limits.
  • Efficient resource usage: By setting time limits, you can ensure your program doesn't consume excessive resources.

Syntax and Usage 📝

The alarm() function has one argument - the number of seconds for which the alarm should be set. Here's the syntax:

c
#include <unistd.h> int alarm(unsigned int seconds);

The function returns the previous alarm value if successful, or -1 if an error occurs.

Example 1: Simple Alarm ✅

Let's create a simple example where we set an alarm for 10 seconds and print a message when the alarm goes off.

c
#include <stdio.h> #include <unistd.h> #include <signal.h> void alarm_handler(int signum) { printf("Alarm went off!\n"); } int main() { signal(SIGALRM, alarm_handler); alarm(10); printf("Setting the alarm for 10 seconds...\n"); pause(); // pause execution until a signal is received printf("Alarm program ended.\n"); return 0; }

In this example, we first define an alarm_handler function that will be called when the alarm signal (SIGALRM) is received. Next, we set the alarm for 10 seconds and create a pause() to wait for the alarm.

Example 2: Alarm with Custom Interval ✅

In this example, we'll create a program that prints the current time every 5 seconds.

c
#include <stdio.h> #include <unistd.h> #include <sys/time.h> #include <signal.h> void alarm_handler(int signum) { struct timeval tv; gettimeofday(&tv, NULL); printf("Current time: %d:%02d:%02d\n", tv.tv_sec, tv.tv_usec / 100000, tv.tv_usec % 100000); } int main() { signal(SIGALRM, alarm_handler); while (1) { alarm(5); pause(); } return 0; }

In this example, we've created an infinite loop where the alarm is set every 5 seconds, and the program pauses until the alarm goes off. Inside the alarm_handler, we get the current time and print it.

Quiz 📝

Quick Quiz
Question 1 of 1

Which header file do you need to include to use the `alarm()` function?