blob: 071a8bfef335fa66e906eca6c38c7ea695b4b9f9 (
plain)
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
|
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
if (argc < 3)
{
fprintf(stderr, "Missing argument\n");
return 2;
}
// Save stdout
int stdout_dup = dup(STDOUT_FILENO);
int file_fd = open(argv[1], O_CREAT | O_WRONLY, 0644);
// Redirect stdout to the file
dup2(file_fd, STDOUT_FILENO);
int status;
pid_t pid = fork();
if (pid == 0)
{
execvp(argv[2], argv + 2);
return 127;
}
else
{
waitpid(pid, &status, 0);
if (WIFEXITED(status))
{
status = WEXITSTATUS(status);
fflush(stdout);
dup2(stdout_dup, STDOUT_FILENO);
close(stdout_dup);
}
if (status != 127)
printf("%s exited with %d!\n", argv[2], status);
else
fprintf(stderr, "Missing command\n");
return status == 127;
}
}
|