-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path18.c
More file actions
89 lines (71 loc) · 2.46 KB
/
18.c
File metadata and controls
89 lines (71 loc) · 2.46 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
============================================================================
Name : 18
Author : Piyush Singh
Description : Write a program to find out total number of directories on the pwd.
execute ls -l | grep ^d | wc ? Use only dup2.
Date: 19th Sep, 2025.
============================================================================
*/
#include <stdio.h> // For perror()
#include <stdlib.h> // For exit()
#include <unistd.h> // For fork(), pipe(), execlp(), dup2()
int main()
{
int pipe1[2], pipe2[2];
// Step 1: Create first pipe for ls -l → grep ^d
// pipe1[1] will carry output of ls -l to grep
pipe(pipe1);
// Step 2: Create second pipe for grep ^d → wc
// pipe2[1] will carry output of grep to wc
pipe(pipe2);
// Step 3: First child process runs ls -l
pid_t pid1 = fork();
if (pid1 == 0)
{
// Redirect stdout to pipe1's write end
dup2(pipe1[1], STDOUT_FILENO); // STDOUT_FILENO = 1
// Close unused pipe ends
close(pipe1[0]); // read end not used by ls
close(pipe1[1]); // already duplicated
close(pipe2[0]); close(pipe2[1]); // not used in this process
// Execute ls -l
execlp("ls", "ls", "-l", NULL);
// If execlp fails
perror("❌ ls failed");
exit(1);
}
// Step 4: Second child process runs grep ^d
pid_t pid2 = fork();
if (pid2 == 0)
{
// Redirect stdin to pipe1's read end
dup2(pipe1[0], STDIN_FILENO); // STDIN_FILENO = 0
// Redirect stdout to pipe2's write end
dup2(pipe2[1], STDOUT_FILENO); // STDOUT_FILENO = 1
// Close unused pipe ends
close(pipe1[0]); close(pipe1[1]); // already duplicated
close(pipe2[0]); close(pipe2[1]); // already duplicated
// Execute grep ^d
execlp("grep", "grep", "^d", NULL);
// If execlp fails
perror("❌ grep failed");
exit(1);
}
// Step 5: Parent process runs wc
// Redirect stdin to pipe2's read end
dup2(pipe2[0], STDIN_FILENO); // STDIN_FILENO = 0
// Close unused pipe ends
close(pipe1[0]); close(pipe1[1]); // not used in parent
close(pipe2[0]); close(pipe2[1]); // already duplicated
// Execute wc
execlp("wc", "wc", NULL);
// If execlp fails
perror("❌ wc failed");
exit(1);
}
/*
Output:
╰─ ./18 ─╯
1 9 66
*/