-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17c.c
More file actions
70 lines (59 loc) · 1.45 KB
/
17c.c
File metadata and controls
70 lines (59 loc) · 1.45 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
/*
============================================================================
Name : 17c
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.
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int pipefd[2];
pipe(pipefd);
pid_t pid = fork();
if (pid < 0)
{
perror("❌ fork failed");
exit(1);
}
// Child: run wc
else if (pid == 0)
{
close(pipefd[1]); // Close write end
close(0); // Close stdin
if (fcntl(pipefd[0], F_DUPFD, 0) == -1)
{
perror("❌ fcntl failed in child");
exit(1);
}
execlp("wc", "wc", NULL);
perror("❌ execlp failed in child");
exit(1);
}
// Parent: run ls -l
else
{
close(pipefd[0]); // Close read end
close(1); // Close stdout
if (fcntl(pipefd[1], F_DUPFD, 1) == -1)
{
perror("❌ fcntl failed in parent");
exit(1);
}
execlp("ls", "ls", "-l", NULL);
perror("❌ execlp failed in parent");
exit(1);
}
}
/*
Output:
╰─ ./17c ─╯
7 56 358
*/