【发布时间】:2013-03-13 21:29:38
【问题描述】:
我目前正在编写一个简单的 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;
}
【问题讨论】:
-
你在哪里检查
active的值? -
我在您的程序中没有看到对
fork()的调用。您是否知道fork实际上复制了所有内容,包括active?默认情况下,两个进程不会共享内存,您必须使用其他一些功能,例如使用SIGCHLD的信号处理程序。 -
@Zeta 我在
newChild()函数中调用fork(),是的,这就是为什么我检查PID 以确保只有父进程可以创建新的子进程 -
newChild()返回什么? -
请将代码发布到
newChild()。