<commit_before><commit_msg>easier to use pipe example<commit_after>
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

void close_pipe(int pipefd [2]);
vector<char *> mk_cstrvec(vector<string> & strvec);

int main(const int argc, const char * argv []) {

  int pipefd [2];
  int pid;

  // create pipe
  if (pipe(pipefd) == -1) {
    perror("pipe");
    exit(EXIT_FAILURE);
  } // if

  if ((pid = fork()) == -1) {
    perror("fork");
    exit(EXIT_FAILURE);
  } else if (pid == 0) {

    if (dup2(pipefd[1], STDOUT_FILENO) == -1) {
      perror("dup2");
      exit(EXIT_FAILURE);
    } // if

    close_pipe(pipefd);

    vector<string> strargs { "cat", "pipe.cpp" };
    vector<char *> cstrargs = mk_cstrvec(strargs);
    execvp(cstrargs.at(0), &cstrargs.at(0));
    
    perror("execvp");
    exit(EXIT_FAILURE);

  } // if

  if ((pid = fork()) == -1) {
    perror("fork");
    exit(EXIT_FAILURE);
  } else if (pid == 0) {

    if (dup2(pipefd[0], STDIN_FILENO) == -1) {
      perror("dup2");
      exit(EXIT_FAILURE);
    } // if

    close_pipe(pipefd);

    vector<string> strargs { "less" };
    vector<char *> cstrargs = mk_cstrvec(strargs);
    execvp(cstrargs.at(0), &cstrargs.at(0));
    
    perror("execvp");
    exit(EXIT_FAILURE);

  } // if

  close_pipe(pipefd);

  waitpid(pid, nullptr, 0);
  return EXIT_SUCCESS;

} // main

void close_pipe(int pipefd [2]) {
  if (close(pipefd[0]) == -1) {
    perror("close");
    exit(EXIT_FAILURE);
  } // if
  if (close(pipefd[1]) == -1) {
    perror("close");
    exit(EXIT_FAILURE);
  } // if
} // close_pipe

vector<char *> mk_cstrvec(vector<string> & strvec) {
  vector<char *> cstrvec;
  for (unsigned int i = 0; i < strvec.size(); ++i) {
    cstrvec.push_back(new char [strvec.at(i).size() + 1]);
    strcpy(cstrvec.at(i), strvec.at(i).c_str());
  } // for
  cstrvec.push_back(nullptr);
  return cstrvec;
} // mk_cstrvec

{'fraction_non_alphanumeric': 0.18948412698412698, 'fraction_numerical': 0.013392857142857142, 'mean_word_length': 3.141683778234086, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 20, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2668899', 'n_tokens_mistral': 822, 'n_tokens_neox': 817, 'n_words': 158}