父进程与子进程之间的 困惑!
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
int main(void)
{
pid_t pid2;
pid_t pid=fork();
if(pid==0)
{
int j ;
for(j=0;j<5;j++)
{
printf("child: %d\n",j);
sleep(1);
}
}
else if (pid>0)
{
int i;
for(i=0;i<5;i++)
{
printf("parent: %d\n",i);
sleep(1);
}
}
else
{
fprintf(stderr,"can't fork ,error %d\n",errno);
exit(1);
}
pid2=fork();
if(pid2==0){printf(" pid2 \n");}
printf("This is the end !\n");
return 0;
}
-------------------------------------------------------------------
./a.out
结果是:jqx2008@jqx55ah:~$ ./a.out
child: 0
parent: 0
child: 1
parent: 1
child: 2
parent: 2
child: 3
parent: 3
child: 4
parent: 4
pid2
This is the end !
pid2
This is the end !
This is the end !
jqx2008@jqx55ah:~$ This is the end !
问题是:一共会产生几个子进程?
输出结果 最后,面那5行怎么解释啊 ?
-------------------------------------------------------
同样这个题目:
./a.out > ty.txt
输出结果却是:
child: 0
child: 1
child: 2
child: 3
child: 4
pid2
This is the end !
parent: 0
parent: 1
parent: 2
parent: 3
parent: 4
pid2
This is the end !
parent: 0
parent: 1
parent: 2
parent: 3
parent: 4
This is the end !
child: 0
child: 1
child: 2
child: 3
child: 4
This is the end !
为什么将结果写进文件 就是这样一个形式了?
大家抽个时间 解释撒!
谢谢哈!
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
int main(void)
{
pid_t pid2;
pid_t pid=fork();
if(pid==0)
{
int j ;
for(j=0;j<5;j++)
{
printf("child: %d\n",j);
sleep(1);
}
}
else if (pid>0)
{
int i;
for(i=0;i<5;i++)
{
printf("parent: %d\n",i);
sleep(1);
}
}
else
{
fprintf(stderr,"can't fork ,error %d\n",errno);
exit(1);
}
pid2=fork();
if(pid2==0){printf(" pid2 \n");}
printf("This is the end !\n");
return 0;
}
-------------------------------------------------------------------
./a.out
结果是:jqx2008@jqx55ah:~$ ./a.out
child: 0
parent: 0
child: 1
parent: 1
child: 2
parent: 2
child: 3
parent: 3
child: 4
parent: 4
pid2
This is the end !
pid2
This is the end !
This is the end !
jqx2008@jqx55ah:~$ This is the end !
问题是:一共会产生几个子进程?
输出结果 最后,面那5行怎么解释啊 ?
-------------------------------------------------------
同样这个题目:
./a.out > ty.txt
输出结果却是:
child: 0
child: 1
child: 2
child: 3
child: 4
pid2
This is the end !
parent: 0
parent: 1
parent: 2
parent: 3
parent: 4
pid2
This is the end !
parent: 0
parent: 1
parent: 2
parent: 3
parent: 4
This is the end !
child: 0
child: 1
child: 2
child: 3
child: 4
This is the end !
为什么将结果写进文件 就是这样一个形式了?
大家抽个时间 解释撒!
谢谢哈!
...全文
相关推荐
使用代码验证linux子进程与父进程的关系
Linux下父进程可以使用fork 函数创建子进程,但是当父进程先退出后,子进程会不会也退出呢?通过下面这个小实验,我们能够很好的看出来
进程通信之三 父进程传参数与子进程返回值
《进程通信之三 父进程传参数与子进程返回值》 http://blog.csdn.net/morewindows/article/details/8683830 配套程序。本篇介绍一个简单而又实用的进程通信方式——父进程向子进程传入参数并获取子进程返回值。这个非常简单: 1.父进程向子进程传入参数可以由CreateProcess()函数来完成,注意子进程是通过GetCommandLine()来获取这个参数而且不是char *argv[]。 2.父进程要获取子进程的返回值可以在等待子进程结束后通过GetExitCodeProcess并传入子进程句柄来获取子进程中main或WinMain函数的返回值。
父进程创建子进程
操作系统实验 父进程创建子进程,显示时间,可选择一个窗口或两个窗口显示
父进程和子进程
这主要是建立子进程,以及对exec()函数的使用,还有在子进程中创建文件
C例子:父进程与子进程
该程序是我写的博客“一起talk C栗子吧(第七十九回:C语言实例--父进程与子进程)”的配套程序,共享给大家使用



