-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17b.c
More file actions
68 lines (58 loc) · 1.42 KB
/
17b.c
File metadata and controls
68 lines (58 loc) · 1.42 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
/*
============================================================================
Name : 17b
Author : Piyush Singh
Description : Write a program to execute ls -l | wc.
a. use dup
b. use dup2
c. use fcntl
Date: 19th Sep, 2025.
============================================================================
*/
// Version B: Use dup2() to redirect ls -l | wc
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
int pipefd[2];
if (pipe(pipefd) == -1)
{
perror("❌ Pipe creation failed");
exit(1);
}
pid_t pid1 = fork();
if (pid1 == 0)
{
// Child 1: ls -l
close(pipefd[0]); // Close read end
dup2(pipefd[1], STDOUT_FILENO); // Redirect stdout to pipe
close(pipefd[1]);
execlp("ls", "ls", "-l", NULL);
perror("❌ exec ls failed");
exit(1);
}
pid_t pid2 = fork();
if (pid2 == 0)
{
// Child 2: wc
close(pipefd[1]); // Close write end
dup2(pipefd[0], STDIN_FILENO); // Redirect stdin to pipe
close(pipefd[0]);
execlp("wc", "wc", NULL);
perror("❌ exec wc failed");
exit(1);
}
// Parent closes both ends and waits
close(pipefd[0]);
close(pipefd[1]);
wait(NULL);
wait(NULL);
return 0;
}
/*
Output:
╰─ ./17b ─╯
6 47 301
*/