此程序用于家庭作业。基本上,从文件中读取文本,并模拟家谱。以下是样本输入和输出:
输入:
A B 3 C D X
D Y 2 M E
M F 0
C P 1 K
输出:
A-B
C-P
K
D-Y
M-F
E
X
基本上,每行的前两个字符都是"夫妇"。然后这个数字代表这对夫妇的孩子数量,然后列出孩子。第一行的夫妇是老大,后面的夫妇可能是其他夫妇的孩子。(很明显,在我的程序实现这一目标之前,我还有很多事情要做)
不管这个程序做什么,我的问题是:对于每个最终有了孩子的孩子,我希望它使用相同的For循环来创建它们。例如,C
-P
对需要在循环ONCE中迭代以创建K
。因此,i
和numChilds
的值被分别设置为0
和1
,使得其迭代一次。但是,一旦循环再次开始迭代,这些值就会被重置。看看我标记为调试的程序的两个部分。这两个地方的变量应该是相同的,但它们会以某种方式恢复到以前的值。也许我不完全理解分叉是如何影响变量范围的,但有人能向我解释一下吗?有没有办法解决这个问题,或者我需要实施一个新的解决方案?
#include <stdio.h>
#include <sys/types.h>
int main (int argc, char* argv[] ){
pid_t pid;
FILE* inFile = fopen(argv[1], "r");
if(inFile==0){
printf( "Error opening file, terminating programn");
return 1;
}
char person;
char partner;
int numChilds;
int inInt;
int i=0;
// boolean flag
int match;
// prime the loop by importing the first two parents
inInt = fgetc(inFile);
while(inInt<33){
inInt = fgetc(inFile);
}
person = (char) inInt;
inInt = fgetc(inFile);
while(inInt<33){
inInt = fgetc(inFile);
}
partner = (char) inInt;
printf("n%c-%cn", person, partner);
// get number of children for first pair
inInt = fgetc(inFile);
while(inInt<33){
inInt = fgetc(inFile);
}
numChilds = inInt - 48;
// loop once for each new child to be created
for(i=0; i<numChilds; i++){
//////////DEBUGGING///////////////////////////////
/*
printf("%i", i);
printf("%i", numChilds);
printf("%c", 'n');
*/
//////////DEBUGGING///////////////////////////////
// get name of next child from file, set it as current person
inInt = fgetc(inFile);
while(inInt<33){
inInt = fgetc(inFile);
}
person = (char) inInt;
pid = fork();
if(pid == 0){ // child process
// search for self in file to find partner
match = 0;
while(((inInt = fgetc(inFile)) != EOF) && match==0){
// if match found
if((char) inInt == person){
// set flag to stop searching file
match = 1;
// grab partner which is next name in file
inInt = fgetc(inFile);
while(inInt<33){
inInt = fgetc(inFile);
}
partner = (char) inInt;
// grab number of children for that pair
inInt = fgetc(inFile);
while(inInt<33){
inInt = fgetc(inFile);
}
numChilds = inInt - 48;
printf("%i", numChilds);
// reset for loop index so it will now execute for child processes
i=0;
}
}
// if partner was never found, child will have no children, so force for loop to stop
if(match==0){
i = numChilds;
}
printf("n%c-%cn", person, partner);
//////////DEBUGGING///////////////////////////////
/*
printf("%i", i);
printf("%i", numChilds);
printf("%c", 'n');
*/
//////////DEBUGGING///////////////////////////////
}
else if(pid>0){ // parent process
wait(NULL);
}
}
return 0;
}
对fork的调用将复制内存中的堆栈(存储变量的位置)和程序(代码),然后在fork程序中的fork调用之后立即运行新进程。
两个分叉的进程将具有不同的堆栈,并将使用不同的变量运行。
你可以阅读http://linux.die.net/man/2/fork以获得分叉行为的完整描述。
要在进程之间进行通信,可以使用共享内存:如何在进程fork()之间共享内存?