Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
/* Same as `repeat-alarm.c` but uses `sleep()` instead of `alarm()`.
*/
/* for clock_gettime() */
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 199309L
#endif
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#define PROGNAME "repeat-alarm"
#define Close(FD) do { \
int Close_fd = (FD); \
if (close(Close_fd) == -1) { \
perror("close"); \
fprintf(stderr, "%s:%d: close(" #FD ") %d\n", \
__FILE__, __LINE__, Close_fd); \
} \
}while(0)
static int report_error(const char* message) {
int n = EOF;
fputs(PROGNAME ": error: ", stderr);
n = fputs(message, stderr);
if (errno != 0)
fprintf(stderr, ": %s\n", strerror(errno));
else
fputs("\n", stderr);
return n;
}
static void
report_error_and_exit_helper(const char* message, void (*exit_func)(int)) {
report_error(message);
exit_func(EXIT_FAILURE);
}
static void report_error_and_exit(const char* message) {
report_error_and_exit_helper(message, exit);
}
static void _report_error_and_exit(const char* message) {
report_error_and_exit_helper(message, _exit);
}
static double perf_counter(struct timespec *tp) {
if (clock_gettime(CLOCK_MONOTONIC, tp) < 0)
report_error_and_exit("perf_counter");
return tp->tv_sec + tp->tv_nsec * 1e-9;
}
/* result = now - start
Return -1 on error.
*/
static int time_difference(struct timespec* pstart, struct timespec* presult) {
struct timespec now = {0};
if (!(pstart && presult))
return -1; /* error */
(void)perf_counter(&now);
{
const long billion = 1000000000;
time_t tv_sec = now.tv_sec - pstart->tv_sec;
long tv_nsec = now.tv_nsec - pstart->tv_nsec; /*XXX overflow? */
/* normalize: 0 <= tv_nsec < billion */
ldiv_t q = ldiv(tv_nsec, billion);
tv_sec += q.quot;
tv_nsec = q.rem;
while (tv_nsec < 0) {
tv_nsec += billion;
tv_sec -= 1;
}
assert(0 <= tv_nsec && tv_nsec < billion);
presult->tv_sec = tv_sec;
presult->tv_nsec = tv_nsec;
}
return 0; /* success */
}
static void write_time(int fd, struct timespec *t) {
ssize_t size = sizeof(*t), n = size, m = 0;
while (n > 0) { /* until there is something to write */
if ((m = write(fd, t + (size - n), n)) != -1)
n -= m;
else if (errno != EINTR)
report_error_and_exit("write");
}
}
int main(void) {
int fd[2];
pid_t pid = -1;
const unsigned total_time = 120, alarm_interval = 15; /* seconds */
if (pipe(fd) == -1)
report_error_and_exit("pipe");
if ((pid = fork()) == -1)
report_error_and_exit("fork");
else if (pid == 0) { /* child */
Close(fd[1]); /* close unused write end of the pipe */
if (fd[0] != STDIN_FILENO) {
/* redirect stdin */
if (dup2(fd[0], STDIN_FILENO) != -1)
Close(fd[0]); /* redirected; don't need it any more */
else
_report_error_and_exit("dup2");
}
{ /* read time from parent and report it */
struct timespec t = {0};
while (fread(&t, sizeof(t), 1, stdin) == 1 &&
printf("Got %" PRIiMAX ".%09ld seconds\n",
(intmax_t)t.tv_sec, t.tv_nsec) > 0);
if (!feof(stdin))
_report_error_and_exit("expected EOF");
}
_exit(EXIT_SUCCESS);
}
/* parent */
Close(fd[0]); /* close unused read end of the pipe */
{ /* until `total_time` seconds pass; sleep for `alarm_interval` seconds;
write `elapsed` time to the pipe `fd[1]`
*/
struct timespec tp = {0}, elapsed = {0};
double start = perf_counter(&tp), endtime = start + total_time;
for ( ; start < endtime; start = perf_counter(&tp)) {
unsigned remaining = alarm_interval;
while ((remaining = sleep(remaining)) > 0)
;
time_difference(&tp, &elapsed);
write_time(fd[1], &elapsed);
}
}
return 0;
}
/*
http://stackoverflow.com/questions/20012279/program-in-c-language-using-pipe-and-fork
Write a program that creates a pipe and a child process. The parent
repeatedly sets an alarm for 15 seconds. When the alarm is triggered,
the parent calculates the number of seconds and microseconds elapsed
since it started and sends these through the pipe to the child. On
obtaining the information the child displays them on the screen. The
whole continues for 2 minutes.
To try it, run:
$ gcc repeat-alarm.c -lrt && ./a.out
*/
/* for clock_gettime() */
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 199309L
#endif
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#define PROGNAME "repeat-alarm"
#define Close(FD) do { \
int Close_fd = (FD); \
if (close(Close_fd) == -1) { \
perror("close"); \
fprintf(stderr, "%s:%d: close(" #FD ") %d\n", \
__FILE__, __LINE__, Close_fd); \
} \
}while(0)
/*
http://www.gnu.org/software/libc/manual/html_node/Handler-Returns.html#Handler-Returns
*/
volatile sig_atomic_t arrived_alarm = 0; /* toggle in alarm signal handler */
/* The signal handler just clears the flag and re-enables itself. */
static void catch_alarm (int sig) {
arrived_alarm = 1;
signal(sig, catch_alarm);
}
static int report_error(const char* message) {
int n = EOF;
fputs(PROGNAME ": error: ", stderr);
n = fputs(message, stderr);
if (errno != 0)
fprintf(stderr, ": %s\n", strerror(errno));
else
fputs("\n", stderr);
return n;
}
static void
report_error_and_exit_helper(const char* message, void (*exit_func)(int)) {
report_error(message);
exit_func(EXIT_FAILURE);
}
static void report_error_and_exit(const char* message) {
report_error_and_exit_helper(message, exit);
}
static void _report_error_and_exit(const char* message) {
report_error_and_exit_helper(message, _exit);
}
static double perf_counter(struct timespec *tp) {
if (clock_gettime(CLOCK_MONOTONIC, tp) < 0)
report_error_and_exit("perf_counter");
return tp->tv_sec + tp->tv_nsec * 1e-9;
}
/* result = now - start
Return -1 on error.
*/
static int time_difference(struct timespec* pstart, struct timespec* presult) {
struct timespec now = {0};
if (!(pstart && presult))
return -1; /* error */
(void)perf_counter(&now);
{
const long billion = 1000000000;
time_t tv_sec = now.tv_sec - pstart->tv_sec;
long tv_nsec = now.tv_nsec - pstart->tv_nsec; /*XXX overflow? */
/* normalize: 0 <= tv_nsec < billion */
ldiv_t q = ldiv(tv_nsec, billion);
tv_sec += q.quot;
tv_nsec = q.rem;
while (tv_nsec < 0) {
tv_nsec += billion;
tv_sec -= 1;
}
assert(0 <= tv_nsec && tv_nsec < billion);
presult->tv_sec = tv_sec;
presult->tv_nsec = tv_nsec;
}
return 0; /* success */
}
static void write_time(int fd, struct timespec *t) {
ssize_t size = sizeof(*t), n = size, m = 0;
while (n > 0) { /* until there is something to write */
if ((m = write(fd, t + (size - n), n)) != -1)
n -= m;
else if (errno != EINTR)
report_error_and_exit("write");
}
}
int main(void) {
int fd[2];
pid_t pid = -1;
const unsigned total_time = 120, alarm_interval = 15; /* seconds */
/* Establish a handler for SIGALRM signals. */
if (signal (SIGALRM, catch_alarm) == SIG_ERR)
report_error_and_exit("signal");
if (pipe(fd) == -1)
report_error_and_exit("pipe");
if ((pid = fork()) == -1)
report_error_and_exit("fork");
else if (pid == 0) { /* child */
Close(fd[1]); /* close unused write end of the pipe */
if (fd[0] != STDIN_FILENO) {
/* redirect stdin */
if (dup2(fd[0], STDIN_FILENO) != -1)
Close(fd[0]); /* redirected; don't need it any more */
else
_report_error_and_exit("dup2");
}
{ /* read time from parent and report it */
struct timespec t = {0};
while (fread(&t, sizeof(t), 1, stdin) == 1 &&
printf("Got %" PRIiMAX ".%09ld seconds\n",
(intmax_t)t.tv_sec, t.tv_nsec) > 0);
if (!feof(stdin))
_report_error_and_exit("expected EOF");
}
_exit(EXIT_SUCCESS);
}
/* parent */
Close(fd[0]); /* close unused read end of the pipe */
{ /* until `total_time` seconds pass; set alarm for `alarm_interval` seconds
write `elapsed` time to the pipe `fd[1]`
*/
struct timespec tp = {0}, elapsed = {0};
double start = perf_counter(&tp), endtime = start + total_time;
for ( ; start < endtime; start = perf_counter(&tp)) {
arrived_alarm = 0; /* reset */
(void)alarm(alarm_interval);
/* sleep until the alarm arrives */
while (!arrived_alarm) { /* arrived_alarm is set in the signal handler */
if (pause() != -1 || errno != EINTR)
report_error_and_exit("pause");
}
time_difference(&tp, &elapsed);
write_time(fd[1], &elapsed);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.