Skip to content

Instantly share code, notes, and snippets.

@swarajd
Created September 22, 2019 01:07
Show Gist options
  • Save swarajd/fc792c80cf05bbb6076e58630b2a17a3 to your computer and use it in GitHub Desktop.
Save swarajd/fc792c80cf05bbb6076e58630b2a17a3 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char** argv) {
// print the args
for (int i = 0; i < argc; ++i) {
printf("%s\n", argv[i]);
}
// keep track of the pids and statuses of the child processes
pid_t first_pid = fork();
pid_t second_pid;
int first_status = 0;
int second_status = 0;
// keep track of the pipes
int first_to_second[2];
int second_to_first[2];
if (pipe(first_to_second) == -1) {
perror("pipe");
exit(1);
}
if (pipe(second_to_first) == -1) {
perror("pipe");
exit(1);
}
//gather arguments for dpipe
char* first_args[2];
first_args[0] = argv[1];
first_args[1] = NULL;
char** second_args = argv + 2;
for (int i = 0; i < argc - 2; i++) {
printf("%s\n", second_args[i]);
}
// this is the first process
if (first_pid == 0) {
printf("in first child process\n");
// reflect the file descriptors properly
if (dup2(first_to_second[1], 1) == -1) {
perror("dup2");
exit(1);
}
close(first_to_second[0]);
close(first_to_second[1]);
if (dup2(second_to_first[0], 0) == -1) {
perror("dup2");
exit(1);
}
close(second_to_first[0]);
close(second_to_first[1]);
// exec with those arguments
execvp(first_args[0], first_args);
}
// this is the parent
else {
printf("in parent process, first child pid: %d\n", first_pid);
second_pid = fork();
// this is the second process
if (second_pid == 0) {
printf("in second child process\n");
// reflect the file descriptors properly
if (dup2(first_to_second[0], 0) == -1) {
perror("dup2");
exit(1);
}
close(first_to_second[0]);
close(first_to_second[1]);
if (dup2(second_to_first[1], 1) == -1) {
perror("dup2");
exit(1);
}
close(second_to_first[0]);
close(second_to_first[1]);
// exec with arguments
execvp(second_args[0], second_args);
} else {
printf("in parent process, second child pid: %d\n", second_pid);
}
waitpid(second_pid, &second_status, 0);
}
waitpid(first_pid, &first_status, 0);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment