以下を機能させるには助けが必要です。C ++からbashプロセスを開始する必要があります。このbashプロセスは、stdinからの入力を受け入れ、通常どおりstdoutに出力する必要があります。
別のプロセスから、上記のように実際に bash で実行される stdin にコマンドを書き込む必要があります。次に、stdout からの結果に興味があります。
これは私がこれまでに試したことですが、出力はまったく意味がありません...
if (pipe(pipeBashShell)) {
fprintf(stderr, "Pipe error!\n");
exit(1);
}
if ((pipePId = fork()) == -1) {
fprintf(stderr, "Fork error. Exiting.\n"); /* something went wrong */
exit(1);
}
if (pipePId == 0) { //this is the child process
dup2(pipeBashShell[0], STDIN_FILENO);
dup2(pipeBashShell[1], STDOUT_FILENO);
dup2(pipeBashShell[1], STDERR_FILENO);
static char* bash[] = {"/bin/bash", "-i", NULL};
if (execv(*bash, bash) == -1) {
fprintf(stderr, "execv Error!");
exit(1);
}
exit(0);
} else {
char buf[512];
memset(buf, 0x00, sizeof(buf));
sprintf(buf, "ls\n");
int byteswritten = write(pipeBashShell[1], buf, strlen(buf));
int bytesRead = read(pipeBashShell[0], buf, sizeof(buf));
write(STDOUT_FILENO, buf, strlen(buf));
exit(0);
}
.
上記の結果の出力は次のとおりです。
' (メイン) bash:: コマンドが見つかりません gerhard@gerhard-work-pc:~/workspaces/si/si$ gerhard orkspaces/si/si$ gerhard@ gerhard-work-pc:~/workspa ....
bash に送信しようとしているコマンドは「ls」です。これにより、ディレクトリの一覧が表示されるはずです。
ここで何か不足していますか?