Use sysexits.h
[oggquiz.git] / player.c
blobdf68b32fe038799d8e088e6b5d8fe2b139e7c710
1 /*-
2 * "THE BEER-WARE LICENSE" (Revision 42):
3 * <tobias.rehbein@web.de> wrote this file. As long as you retain this notice
4 * you can do whatever you want with this stuff. If we meet some day, and you
5 * think this stuff is worth it, you can buy me a beer in return.
6 * Tobias Rehbein
7 */
9 #include <assert.h>
10 #include <err.h>
11 #include <signal.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sysexits.h>
15 #include <unistd.h>
16 #include <sys/types.h>
18 #include "player.h"
20 struct plr_context {
21 char *ogg123;
22 pid_t pid;
25 struct plr_context *
26 plr_context_open(char const *ogg123)
28 struct plr_context *ctx;
29 size_t ogg123len;
31 assert(ogg123 != NULL);
33 if ((ctx = malloc(sizeof(*ctx))) == NULL)
34 err(EX_SOFTWARE, "could not malloc plr_ctx");
36 ogg123len = strlen(ogg123);
37 if ((ctx->ogg123 = malloc(ogg123len + 1)) == NULL)
38 err(EX_SOFTWARE, "could not malloc plr_ctx->ogg123");
39 strncpy(ctx->ogg123, ogg123, ogg123len);
40 ctx->ogg123[ogg123len] = '\0';
42 ctx->pid = (pid_t) - 1;
44 return (ctx);
47 void
48 plr_context_close(struct plr_context *ctx)
50 assert(ctx != NULL);
52 plr_stop(ctx);
53 free(ctx->ogg123);
54 free(ctx);
57 void
58 plr_play(struct plr_context *ctx, char *ogg)
60 pid_t lpid;
62 assert(ctx != NULL);
63 assert(ogg != NULL);
65 plr_stop(ctx);
67 switch (lpid = fork()) {
68 case (0):
69 execl(ctx->ogg123, ctx->ogg123, "-q", ogg, NULL);
70 err(EX_OSERR, "could not exec %s", ctx->ogg123);
71 case (-1):
72 err(EX_OSERR, "could not fork player");
73 default:
74 ctx->pid = lpid;
78 void
79 plr_stop(struct plr_context *ctx)
81 if (ctx->pid != (pid_t) (-1)) {
82 if (kill(ctx->pid, SIGHUP))
83 err(EX_OSERR, "could not kill running player: %d", ctx->pid);
84 ctx->pid = -1;