Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist
View repeat-alarm-sleep.c
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
/* 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;
}
View repeat-alarm-sleep.c
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
/*
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.