Skip to content

Instantly share code, notes, and snippets.

@imasusen
Last active August 29, 2015 14:10
Show Gist options
  • Save imasusen/3024cd77d183aa7d631a to your computer and use it in GitHub Desktop.
Save imasusen/3024cd77d183aa7d631a to your computer and use it in GitHub Desktop.
#include <sys/types.h>
#include <stdio.h> // perror
#include <string.h> // strlen
#include <unistd.h> // pipe2, dup, dup2, fork, read, close
#include <fcntl.h> // O_CLOEXEC flag
#include <signal.h> // kill
#include <iostream>
#include <string>
using namespace std;
int main() {
// パイプ(・㉨・)
int pipefd[2]; // 0:read, 1:write
pipe2(pipefd, O_CLOEXEC);
const int pid = fork();
if (pid == -1) {
perror("fork");
return -1;
}
if (pid == 0) {
// 子プロセス
close(pipefd[0]);
// 標準出力、標準エラーをパイプにリダイレクトさせる
int old_stdout, old_stderr;
old_stdout = dup(STDOUT_FILENO);
old_stderr = dup(STDERR_FILENO);
dup2(pipefd[1], STDOUT_FILENO);
dup2(pipefd[1], STDERR_FILENO);
while (1) {
cout << "a";
}
cout << " (^-^)/" << endl;
}
// 親プロセス
close(pipefd[1]);
// 子プロセスが出力してるものを読んでく
const int bufsize = 1024;
const int output_limit = 128*1024;
char buf[bufsize] = "";
std::string output = "";
while (read(pipefd[0], buf, bufsize) > 0) {
output += buf;
// 出力量が多かったら子プロセスを終わらす
if (strlen(output.c_str()) > output_limit) {
kill(pid, SIGXFSZ);
output += "\n出力過多";
break;
}
}
close(pipefd[0]);
// 子プロセスが出力した内容を表示
cout << output << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment