我目前正在编写一个简单的 C 程序来从父进程创建指定数量的子进程,并且我试图通过每次增加变量active来跟踪其中有多少子进程实际上成功启动了一个孩子-进程成功。
但是,#!%€ 变量的愚蠢部分不允许我修改它。我是 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;
}