Skip to content

Commit 14728a4

Browse files
committed
Add quiz/run
1 parent d46888b commit 14728a4

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

quiz/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,5 @@ add_exe(eight_queen eight_queen.c)
1717
add_exe(horse_move horse_move.c)
1818
add_exe(logic_question logic_question.c)
1919
add_exe(nine_interlocking_rings nine_interlocking_rings.c)
20+
add_exe(run run.c)
2021
add_exe(sudoku sudoku.c)

quiz/run.c

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <errno.h>
2+
#include <stdarg.h>
3+
#include <stdbool.h>
4+
#include <stdio.h>
5+
#include <stdlib.h>
6+
#include <string.h>
7+
#include <unistd.h>
8+
9+
#include <sys/wait.h>
10+
11+
static void log_err(const char *fmt, ...)
12+
{
13+
va_list args;
14+
va_start(args, fmt);
15+
vfprintf(stderr, fmt, args);
16+
fputc('\n', stderr);
17+
va_end(args);
18+
}
19+
20+
static bool run_cmd(int argc, char *argv[])
21+
{
22+
if (argc < 2) {
23+
log_err("No command given");
24+
return false;
25+
}
26+
pid_t pid = fork();
27+
if (pid < 0) {
28+
log_err("Cannot run command: fork failed: %s", strerror(errno));
29+
return false;
30+
} else if (pid == 0) {
31+
/* Generally the first argument is itself, so skip it */
32+
if (execvp(argv[1], &argv[1]) < 0) {
33+
log_err("Cannot run command: %s", strerror(errno));
34+
}
35+
exit(EXIT_FAILURE);
36+
}
37+
return true;
38+
}
39+
40+
int main(int argc, char *argv[])
41+
{
42+
run_cmd(argc, argv);
43+
wait(NULL);
44+
}

0 commit comments

Comments
 (0)