私は現在、親プロセスから指定された数の子プロセスを作成する単純な C プログラムを作成しています。実際に正常に開始された子プロセスの数を追跡しようとしています。 -プロセスは成功しました。
ただし、 #!%€ 変数の愚かな部分では、それを変更できません.. 私は C を初めて使用し (したがって、プログラムの単純さと使いやすさに疑問があります)、別の変数を理解するのに少し問題があります。変数スコープと、いつ、どのように変更して、新しい値が固定されるようにするか...
それで、私の質問は次のとおりです。変数「アクティブ」を 1 増やすにはどうすればよいですか?
newChild() 関数が必要に応じて 1 を返し、その if ステートメント内の他のコードが機能することを既に確認しているので、そうではありません。また、ポインターを使用してみましたが、成功しませんでした... :(
# include <stdio.h>
# include <unistd.h>
# include <stdlib.h>
# include <sys/wait.h>
main()
{
printf("Parent CREATED\nRunning code...\n");
// INITIATE Variables
int children = 5;
int active = 0;
int parentID = getpid();
// INITIATE Random Seed
srand(time(NULL));
// CREATE Children
int i, cpid, sleepTime;
for (i = 0; i < children; i++)
{
// Only let the parent process create new children
if (getpid() == parentID)
{
// GET Random Number
sleepTime = rand() % 10;
// CREATE Child
if (newChild(sleepTime) == 1)
{
// Mark as an active child process
active++;
}
}
}
// CLEAN UP
if (getpid() == parentID)
{
// Let the parent process sleep for a while...
printf("Parent is now SLEEPING for 20 seconds...\n");
sleep(20);
printf("Parent is now AWAKE\nActive children: %d\n", active);
// WAIT for Children
int cpid, i;
int status = 0;
for (i = 0; i < active; i++)
{
// WAIT for Child
cpid = wait(&status);
// OUTPUT Status
printf("WAITED for Child\nID: %d, Exit Status: %d\n", cpid, status);
}
printf("All children are accounted for.\nEXITING program...\n");
}
}
int newChild(int sleepTime)
{
// INITIATE Variable
int successful = 0;
// CREATE Child Process
int pid = fork();
if (pid == -1)
{
// OUTPUT Error Message
printf("The child process could not be initiated.");
}
else if (pid == 0)
{
// Mark child process as successfully initiated
successful = 1;
// OUTPUT Child Information
printf("Child CREATED\nID: %d, Parent ID: %d, Group: %d\n", getpid(), getppid(), getpgrp());
// Let the child process sleep for a while...
printf("Child %d is now SLEEPING for %d seconds...\n", getpid(), sleepTime);
sleep(sleepTime);
printf("Child %d is now AWAKE\n", getpid());
}
return successful;
}