/* * This code is identical to running * w | wc -w * in bash */ #include #include 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); } }