Skip to content

Instantly share code, notes, and snippets.

@marionette-of-u
Created April 30, 2014 16:54
Show Gist options
  • Select an option

  • Save marionette-of-u/18011feed423ba975598 to your computer and use it in GitHub Desktop.

Select an option

Save marionette-of-u/18011feed423ba975598 to your computer and use it in GitHub Desktop.
popen2は新しくプログラムを起動してその入出力を奪う。どこかのサイトからのこぴぺなんだけど失念してしまいました。
#include <unistd.h>
#include <netdb.h>
#include <dirent.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fstream>
#include <iostream>
#include <string>
#include <map>
#define R 0
#define W 1
char pipebuf[0x1000];
int popen2(const char *command, int *pfd){
int pipe_c2p[2], pipe_p2c[2];
pid_t pid;
if(pipe(pipe_c2p) < 0){
perror("popen2");
return -1;
}
if(pipe(pipe_p2c) < 0){
perror("popen2");
close(pipe_c2p[R]), close(pipe_c2p[W]);
return -1;
}
if((pid = fork()) < 0){
perror("popen2");
close(pipe_c2p[R]), close(pipe_c2p[W]);
close(pipe_p2c[R]), close(pipe_p2c[W]);
return -1;
}
if(pid == 0){
close(pipe_p2c[W]), close(pipe_c2p[R]);
dup2(pipe_p2c[R], STDIN_FILENO);
dup2(pipe_c2p[W], STDOUT_FILENO);
close(pipe_p2c[R]), close(pipe_c2p[W]);
if(execlp("sh", "sh", "-c", command, NULL) < 0){
perror("popen2");
close(pipe_p2c[R]), close(pipe_c2p[W]);
exit(-1);
}
}
close(pipe_p2c[R]), close(pipe_c2p[W]);
pfd[R] = pipe_c2p[R];
pfd[W] = pipe_p2c[W];
return pid;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment