-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist.c
More file actions
56 lines (49 loc) · 1.44 KB
/
list.c
File metadata and controls
56 lines (49 loc) · 1.44 KB
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
47
48
49
50
51
52
53
54
// Worked on by Tenzen Sherpa
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#define READ_END 0
#define WRITE_END 1
void sh_list(char **args) {
system("clear"); //Clear Screen();
int file_desc = open("t1.txt", O_WRONLY | O_CREAT, 0666);
int pid_ls = fork(); // Fork a process to run ls -l
if (pid_ls < 0){
fprintf(stderr, "parent: Could not fork process to run ls\n");
exit(0);
}
else if (pid_ls == 0){
// Child
dup2(file_desc, 1);
// Setup the arguments/environment to call
char *new_argv[] = {"ls", "-l", 0};
// Call execvp() which will replace the executable image of this
// process
execvp(new_argv[0], new_argv);
// Execution will never continue in this process unless execve returns
// because of an error
fprintf(stderr, "child ls -l failed!\n");
exit(0);
} else {
// Parent
close(file_desc);
// Wait for children to finish
wait(NULL);
// open file and print to stdout
FILE *file = fopen("t1.txt", "r");
if (file == NULL) {
printf("File t1.txt not found.\n");
exit(0);
}
char c;
c = fgetc(file);
while (c != EOF) {
printf("%c", c);
c = fgetc(file);
}
fclose(file);
rename("t1.txt", "tree.txt"); // rename file
}
}