【发布时间】:2010-12-16 10:25:46
【问题描述】:
系统信息:我在 2 个月大的笔记本电脑上运行 64 位 Ubuntu 10.10。
大家好,我有一个关于 C 中的 fork() 函数的问题。从我使用的资源(Stevens/Rago、YoLinux 和 Opengroup)来看,我的理解是,当您分叉一个进程时,两者父母和孩子从下一个命令继续执行。由于fork() 将0 返回给子进程,而子进程的进程ID 将返回给父进程,因此您可以使用两个if 语句来区分他们的行为,一个if(pid == 0) 代表子进程,一个if(pid > 0),假设您使用@ 分叉987654326@.
现在,我遇到了最奇怪的事情。在我的 main 函数开始时,我打印到 stdout 几个已分配给变量的命令行参数。这是整个程序中的第一个非赋值语句,然而,似乎每次我在程序后面调用fork时,都会执行这些打印语句。
我的程序的目标是创建一个“进程树”,每个进程有两个子进程,深度为 3,从而创建初始可执行文件的总共 15 个子进程。每个进程在分叉前后打印其父进程 ID 及其进程 ID。
我的代码如下并已正确注释,命令行参数应为"ofile 3 2 -p"(我还没有实现-p/-c标志):
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
if(argc != 5)//checks for correct amount of arguments
{
return 0;
}
FILE * ofile;//file to write to
pid_t pid = 1;//holds child process id
int depth = atoi(argv[2]);//depth of the process tree
int arity = atoi(argv[3]);//number of children each process should have
printf("%d%d", depth, arity);
ofile = fopen(argv[1], "w+");//opens specified file for writing
int a = 0;//counter for arity
int d = 0;//counter for depth
while(a < arity && d < depth)//makes sure depth and arity are within limits, if the children reach too high(low?) of a depth, loop fails to execute
//and if the process has forked arity times, then the loop fails to execute
{
fprintf(ofile, "before fork: parent's pid: %d, current pid: %d\n", getppid(), getpid());//prints parent and self id to buffer
pid = fork(); //forks program
if(pid == 0)//executes for child
{
fprintf(ofile, "after fork (child):parent's pid: %d, current pid: %d\n", getppid(), getpid());//prints parent's id and self id to buffer
a=-1;//resets arity to 0 (after current iteration of loop is finished), so new process makes correct number of children
d++;//increases depth counter for child and all of its children
}
if(pid > 0)//executes for parent process
{
waitpid(pid, NULL, 0);//waits on child to execute to print status
fprintf(ofile, "after fork (parent):parent's pid: %d, current pid: %d\n", getppid(), getpid());//prints parent's id and self id to buffer
}
a++;//increments arity counter
}
fclose(ofile);
}
当我运行gcc main.c -o ptree 然后ptree ofile 3 2 -p 时,控制台被"32" 看似无限地重复,并且文件ofile 的格式看似正确,但对于我认为我的程序应该的来说太大了正在做。
任何帮助将不胜感激。
【问题讨论】:
-
别忘了
fflush(NULL);就在之前fork()