Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / System programming / Practicum5 / ex6.c
blob: 86e206c6e6fe3992472d52ee0e876c5e719eba8b (plain) (blame)
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
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
	pid_t f = fork();
	if (f < 0) {
		perror("fork");
		return 1;
	}

	if (f == 0) {
		char *commargs[argc];
		commargs[0] = argv[1];
		for (int i = 0; i < argc - 2; i++)
			commargs[i+1] = argv[i+1];
		commargs[argc - 1] = NULL;

		int w = open(argv[argc-1], O_WRONLY | O_CREAT, 0755);
		dup2(w, 1);
		close(w);
		execvp(*commargs, commargs + 1);
	}
	else {
		int status = -2;
		wait(&status);
		printf("Exit: %d\n", status);
	}
}