Add w2wc pipe

This commit is contained in:
Akemi Izuko 2024-09-24 15:52:03 -06:00
parent 8d07fc6fef
commit 207c258ddb
Signed by: akemi
GPG key ID: 8DE0764E1809E9FC
2 changed files with 91 additions and 0 deletions

51
lab2/demos/w2wc.c Normal file
View file

@ -0,0 +1,51 @@
/*
* This code is identical to running
* w | wc -w
* in bash
*/
#include <stdio.h>
#include <unistd.h>
void child(int pfd[2]) {
close(pfd[1]);
dup2(pfd[0], STDIN_FILENO);
close(pfd[0]);
char cmd[] = "/usr/bin/wc";
char *args[] = {"wc", "-w", NULL};
if (execve(cmd, args, NULL) == -1) {
perror("wc error!");
}
}
void parent(int pfd[2]) {
close(pfd[0]);
dup2(pfd[1], STDOUT_FILENO);
close(pfd[1]);
char cmd[] = "/usr/bin/w";
char *args[] = {"w", NULL};
if (execve(cmd, args, NULL) == -1) {
perror("w error!");
}
}
int main (void) {
int pfd[2];
if (pipe(pfd) < 0) {
perror("pipe error!");
_exit(1);
}
int pid = fork();
if (pid < 0) {
perror("fork error!");
_exit(1);
}
if (pid == 0) { // child
child(pfd);
} else {
parent(pfd);
}
}

40
lab2/demos/w2wc_short.c Normal file
View file

@ -0,0 +1,40 @@
/*
* This code is identical to running
* w | wc -w
* in bash
*/
#include <stdio.h>
#include <unistd.h>
void child(int pfd[2]) {
close(pfd[1]);
dup2(pfd[0], STDIN_FILENO);
close(pfd[0]);
char cmd[] = "/usr/bin/wc";
char *args[] = {"wc", "-w", NULL};
execve(cmd, args, NULL);
}
void parent(int pfd[2]) {
close(pfd[0]);
dup2(pfd[1], STDOUT_FILENO);
close(pfd[1]);
char cmd[] = "/usr/bin/w";
char *args[] = {"wc", NULL};
execve(cmd, args, NULL);
}
int main (void) {
int pfd[2];
pipe(pfd);
int pid = fork();
if (pid == 0) {
child(pfd);
} else {
parent(pfd);
}
}