所以我无法弄清楚这个程序的输出,因为我很困惑什么决定孩子被执行的时间和父母的时间。
int i, n =6;
for(int i =0; i<4; i++)
fork();
n++;
printf("n is %d\n", n);
答案 0 :(得分:0)
这是胡说八道:
int i, n =6;
for(int i =0; i<4; i++)
fork();
n++;
printf("n is %d\n", n);
推荐:
以下代码:
现在代码:
#include <stdio.h> // printf(), perror()
#include <stdlib.h> // exit(), EXIT_SUCCESS, EXIT_FAILURE
#include <unistd.h> // fork(), pid_t
#include <sys/types.h>
#include <sys/wait.h> // waitpid()
#define MAX_CHILDS 4
int main( void )
{
pid_t pid[ MAX_CHILDS ] = {0};
for(int i =0; i<MAX_CHILDS; i++)
{
pid[i] = fork();
switch( pid[i] )
{
case 0: // child
printf( "I am child: %d\n", i );
exit( EXIT_SUCCESS );
break;
case -1: // error
perror( "fork failed" );
// exit( EXIT_FAILURE );
break;
default: // parent
printf( "I am the parent\n" );
break;
} // end switch()
}
// wait for each child to exit before parent exits
// so no child becomes a zombie process
for( int i=0; i<MAX_CHILDS; i++ )
{
int status;
// only wait on a child process if it was actually created
if( pid[i] != -1 )
{
waitpid( pid[i], &status, 0);
}
}
} // end function: main