-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17a.c
More file actions
75 lines (63 loc) · 1.65 KB
/
17a.c
File metadata and controls
75 lines (63 loc) · 1.65 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
/*
============================================================================
Name : 17a
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 A: Use dup() to redirect ls -l | wc
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
int pipefd[2];
// Create pipe
if (pipe(pipefd) == -1)
{
perror("❌ Pipe creation failed");
exit(1);
}
// Fork first child for ls -l
pid_t pid1 = fork();
if (pid1 == 0)
{
// Child 1: ls -l
close(pipefd[0]); // Close read end
// Redirect stdout to pipe write end using dup()
close(1); // Close stdout
dup(pipefd[1]); // Duplicate pipefd[1] to stdout (fd 1)
execlp("ls", "ls", "-l", NULL);
perror("❌ exec ls failed");
exit(1);
}
// Fork second child for wc
pid_t pid2 = fork();
if (pid2 == 0)
{
// Child 2: wc
close(pipefd[1]); // Close write end
// Redirect stdin to pipe read end using dup()
close(0); // Close stdin
dup(pipefd[0]); // Duplicate pipefd[0] to stdin (fd 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:
╰─ ./17a ─╯
5 38 243
*/