次のコード例は実行されますが、フォークされたプロセスからの出力は読み込めません。Enterを押してから「読み込みに失敗しました」までは何も表示されません。示しています。fork()のプロセス内のIOストリーム
質問:それはなぜですか、fork()
のプロセスからstdin
とstdout
と対話するにはどうすればよいですか?
/* example1.c */
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main() {
pid_t pid = fork();
if (!pid) {
// child
char s[64];
printf("Enter something: ");
char *res = fgets(s, 64, stdin);
if (!res) {
printf("Read failed!\n");
} else {
printf("You entered: %s", s);
}
}
return 0;
}
更新:IOの奇妙な行動の別の例は、ストリーム
:
/* example2.c */
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main() {
pid_t pid = fork();
if (!pid) {
// child
char *argv[] = {
"-c",
"/home/user/echo.sh",
NULL
};
execv("/bin/sh", argv);
}
return 0;
}
echo.sh
スクリプト:
#!/bin/sh
read -p "Enter something: " INPUT
echo "You entered $INPUT"
この1つは
を返します。Enter something: /home/user/echo.sh: line 3: read: read error: 0: Input/output error
You entered
アップデート2:
は、このコードが必要なのは、正確に何を次のようになります。
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main() {
pid_t pid = vfork();
if (!pid) {
// child
system("/home/user/echo.sh");
}
return 0;
}
ソリューションはvfork
でfork
を交換しました。私はちょうどなぜこれが働いているのか分かりません...
おそらく、親が子が終了する前に終了していますか? –
@ 0A0D:ありがとう、これがそうであるように、問題は 'fork()'/'execv'の代わりに' system() 'を使って簡単に解決できます。しかし、IOストリームを継承する別のプロセスで実行可能ファイルをどのように起動するのですか?私は子供が出るのを待つことなく、いつでも親プロセスを殺すことができる必要があります。 – Andy
@Andy - 'vfork'は、子プロセスが終了するまで呼び出しプロセスを中断します。これは親プロセスで 'wait'を呼び出すのとまったく同じです。 – Seth