Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / System programming / Practice05 / ex7.c
blob: 08df36799721d51c4e608fcf27d4b18a6beca52d (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
31
#include <unistd.h> // execvp, fork
#include <stdio.h> // printf
#include <sys/wait.h> // wait
#include <fcntl.h> // open, O_WRONLY

int main(int argc, char* argv[]) {
	if (argc < 2) return 1;

	pid_t fpid = fork();
	if (fpid == 0) {
		int f = open(argv[argc-1], O_WRONLY | O_TRUNC | O_CREAT, 0755);
		if (f < 0) {
			perror("open");
			return 2;
		}
		dup2(f, 1);
		close(f);

		char* args[argc-1];
		for (int i = 1; i < argc - 1; i++)
			args[i-1] = argv[i];
		args[argc-2] = NULL;

		execvp(argv[1], args);
	}
	else {
		int status;
		wait(&status);
		printf("%d %d\n", fpid, status);
	}
}