私は入力としてXとYの2つの整数値を受け付けるプログラムを書いています(これは割り当て用です)。親プロセスが子プロセスの前にscanf()を実行する方法を教えてください。
難しい部分は、親プロセスがXを読み取り、子プロセスがY(scanf
を使用)を読み取る親と子を作成する必要があるということです。
プログラムの予想される出力は次のとおりです:
From parent 2255: child with PID 2256 is created
From parent 2255: Reading X from the user
>> 99
>> X in parent is 99
From child: Reading Y from the user
>> 88
>> Y in child is 88
私がいる問題は子供が自動的に実行し、入力が親に受信されるまで待機しないということです。
私の教授は、この問題を解決するために子プロセスの開始時にsleep()を使用できるというヒントを示しましたが、私は運がありません。
私のサンプルコード(動作しない):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h> // pid_t
#include <unistd.h> // NULL, fork()
#include <errno.h> // errno
int main(void){
// Initializing variables
int X = 0, Y = 0;
// Fork
pid_t pid;
pid = fork();
// ERROR
if (pid < 0){
// error handling
}
// PARENT
else if (pid > 0){
// Read X
printf("From parent %d: Reading X from the user\n>> ", pid);
scanf(" %d", &X);
printf("X in parent is %d\n", X);
// Some other code afterwards
}
// CHILD
else {
// Read Y
printf("From child: Reading Y from the user\n>> ");
scanf(" %d", &Y);
printf("Y in child is %d\n", Y);
// Some other code afterwards
}
return 0;
}
私は本当に任意の助けをいただければ幸いです。ありがとうございました!子供が終了するのを
複数のプロセスによるリソースへのアクセスを同期させる1つの方法は、セマフォを使用して行うことができます。もう1つは、親と子の間にパイプを作成している可能性があります。子は、そのscanfが完了したときに親によって送信されるパイプ上の "進む"メッセージを待ちます。 – TonyB
子プロセスの開始時にsleepを呼び出すのはお粗末なコーディングですが、それがあなたの教授が望んでいるものなら、なぜあなたはそれをしませんか? – rici
@rici子プロセスの開始時に 'sleep(5)'を追加すると、プログラムは親のコードを実行し、残念ながら終了します。 –