joe*_*ian 2 c linux fork process
系统信息:我在2个月大的笔记本电脑上运行64位Ubuntu 10.10.
大家好,我对fork()C中的功能有疑问.从我正在使用的资源(Stevens/Rago,YoLinux和Opengroup)我理解当你分叉一个进程时,父进程和子进程都继续执行从下一个命令.由于fork()返回0到子节点,以及子节点到父节点的进程ID,您可以使用两个if语句来分散它们的行为,一个if(pid == 0)用于子节点,并if(pid > 0)假设您分叉pid = fork().
现在,我发生了最奇怪的事情.在我的main函数的开头,我打印到stdout几个已分配给变量的命令行参数.这是整个程序中的第一个非赋值语句,但是,似乎每次我fork在程序中稍后调用时,都会执行这些print语句.
我的程序的目标是创建一个"进程树",每个进程有两个子进程,深度为3,从而创建初始可执行文件的15个子进程.每个进程在fork之前和之后打印它的父进程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);
}
Run Code Online (Sandbox Code Playgroud)
当我跑 gcc main.c -o ptree那么ptree ofile 3 2 -p,控制台垃圾邮件与"32"重复看似无限,并且该文件ofile似乎是适当的格式,但远远什么,我认为我的节目应该做的太大.
任何帮助将不胜感激.
我不知道为什么要为孩子们执行fputsto stdout,并且没有Unix盒子来验证/测试.
但是,以下跳出:
int depth = *argv[2];//depth of the process tree
int arity = *argv[3];//number of children each process should have
Run Code Online (Sandbox Code Playgroud)
你正在服用的第一个字符的ASCII码argv[2],并argv[3]为您depth和arity,所以你的代码试图产卵50^51的过程,而不是2^3.
你想要的是:
int depth = atoi(argv[2]);//depth of the process tree
int arity = atoi(argv[3]);//number of children each process should have
Run Code Online (Sandbox Code Playgroud)
一旦你解决了这个问题,bleh[0] = depth它的双胞胎也需要纠正.
编辑虽然现在这不是一个问题,但是你要根据你sprintf正在进行的一些事情的长度来削减它obuf.让一些消息更长一点,Kaboom!至少你想直接使用snprintf或更好地使用fprintf文件.
编辑我刚才意识到fork,作为一个操作系统功能,很可能不知道CI/O功能完成内部缓冲.这可以解释为什么你会得到重复项(父和子都获得缓冲数据的副本fork).fflush(stdout)在循环之前尝试.此外fflush(ofile)每前fork.