ºìÁªLinuxÃÅ»§
Linux°ïÖú

linux¶à½ø³ÌµÄ×ܽᣨforkÓ÷¨£©

·¢²¼Ê±¼ä:2008-05-23 12:35:41À´Ô´:ºìÁª×÷Õß:lixceo
Ô­´´£ºlobbve223

¼òµ¥Àí½âΪ£¬Ò»¸ö½ø³Ì±íʾµÄ£¬¾ÍÊÇÒ»¸ö¿ÉÖ´ÐгÌÐòµÄÒ»´ÎÖ´Ðйý³ÌÖеÄÒ»¸ö״̬¡£²Ù×÷ϵͳ¶Ô½ø³ÌµÄ¹ÜÀí£¬µäÐ͵ÄÇé¿ö£¬ÊÇͨ¹ý½ø³Ì±íÍê³ÉµÄ¡£½ø³Ì±íÖеÄÿһ¸ö±íÏ¼Ç¼µÄÊǵ±Ç°²Ù×÷ϵͳÖÐÒ»¸ö½ø³ÌµÄÇé¿ö¡£¶ÔÓÚµ¥ CPUµÄÇé¿ö¶øÑÔ£¬Ã¿Ò»Ìض¨Ê±¿ÌÖ»ÓÐÒ»¸ö½ø³ÌÕ¼Óà CPU£¬µ«ÊÇϵͳÖпÉÄÜͬʱ´æÔÚ¶à¸ö»î¶¯µÄ£¨µÈ´ýÖ´Ðлò¼ÌÐøÖ´Ðеģ©½ø³Ì¡£

fork()ÓÃÓÚ´ÓÒÑ´æ½ø³ÌÖн¨Á¢Ò»¸öнø³Ì,нø³ÌΪ×Ó½ø³Ì,ÀϽø³ÌΪ¸¸½ø³Ì.¿ÉÒÔͨ¹ý¼ì²é"fork()"µØ·µ»ØÖµÖªµÀÄĸöÊÇ×Ó½ø³ÌÄĸöÊǸ¸½ø³Ì¡£¸¸½ø³ÌµÃµ½µÄ·µ»ØÖµÊÇ×Ó½ø³ÌµÄ½ø³ÌºÅ£¬¶ø×Ó½ø³ÌÔò·µ»Ø0¡£

»ù±¾Ä£Ê½ÊÇ£º

#include
#include
#include
#include
#include
#include
main()
{
pid_t pid;
int rv;
pid=fork()£» //´´½¨½ø³Ì
switch(pid)
{
case -1: //·µ»Ø-1µÄ»°£¬½ø³Ì´´½¨Ã»³É¹¦
perror("fork");
exit(1);
case 0:
printf(" CHILD: This is the child process!\n");
printf(" CHILD: My PID is %d\n", getpid()); //µ÷Óà getpid µÃµ½×Ô¼ºµÄ PID
printf(" CHILD: My parent's PID is %d\n", getppid()); //getppid() µÃµ½¸¸½ø³ÌµÄ PID
printf(" CHILD: Enter my exit status (make it small): ");
scanf(" %d", &rv);
printf(" CHILD: I'm outta here!\n");
exit(rv);
default:
printf("PARENT: This is the parent process!\n");
printf("PARENT: My PID is %d\n", getpid());
printf("PARENT: My child's PID is %d\n", pid); //fork() ·µ»ØµÄdefaultÖµÒâζ×ÅÄãÕýÔÚ¸¸½ø³ÌÖУ¬·µ»ØÖµÊÇ×Ó½ø³ÌµÄ PID ¡£ÕâÊǵõ½×Ó½ø³Ì PID µÄΨһ·½·¨
printf("PARENT: I'm now waiting for my child to exit()...\n");
wait(&rv); //¸¸½ø³Ì±ØÐëµÈ´ý×Ó½ø³ÌÍê³ÉÊÕÊ°×Ó½ø³ÌµÄ²ÐÓàºó²ÅÄܼÌÐø
printf("PARENT: My child's exit status is: %d\n", WEXITSTATUS(rv)); Ò²¾ÍÊǸ¸½ø³Ì²»ÄÜÏÈÓÚ×Ó½ø³ÌÏûÍö¡£
printf("PARENT: I'm outta here!\n");
}
}
//EXITSTATUS() ÊÇÒ»¸öºê£¬´Ó wait() ·µ»ØÖµÖÐÌáȡʵ¼ÊµÄ·µ»ØÖµ¡£
// wait() Ôõô֪µÀÔÚÄĸö½ø³ÌÉϵȴý£¿ÎÒµÄÒâ˼ÊÇ£¬ÓÉÓÚ¸¸½ø³Ì¿ÉÒÔÓжà¸ö×Ó½ø³Ì£¬ wait() ʵ¼ÊµÈ´ýµØÊÇÄÄÒ»¸ö£¿´ð°¸·Ç³£¼òµ¥£¬ËüµÈ´ý×îÏÈÍ˳öµÄÄÇÒ»¸ö¡£Äã¿ÉÒÔͨ¹ýÒÔ×Ó½ø³ÌµÄ PID Ϊ²ÎÊýµ÷Óà waitpid() Ö¸Ã÷ÊÇÄÄÒ»¸ö×Ó½ø³Ì¡£

if (!fork())
{
printf("I'm the child!\n");
exit(0);
} else
{
printf("I'm the parent!\n");
wait(NULL);
}

linux ÊǶàÓû§ºÍ¶à½ø³ÌµÄ²Ù×÷ϵͳ£¬½ø³ÌÔÚ²Ù×÷ϵͳÖеĴ´½¨£¬¶¼»áÉú³ÉÒ»¸ö½ø³ÌÃèÊö¿é£¬ÃèÊöµ±Ç°½ø³ÌµÄËùÓÐÐÅÏ¢£¬°üÀ¨£¬Êý¾Ý¶Î¡¢´úÂë¶Î¡¢¶ÑÕ»¶ÎµÄµØÖ·£¬µ±Ç°½ø³ÌµÄ»·¾³±äÁ¿£¬ÎļþÃèÊö·ûµÈ¡£

forkº¯Êý¹ý³Ì£º²Ù×÷ϵͳÏÈ´´½¨Ò»¸ö½ø³ÌÃèÊö¿é£¬È»ºó°Ñ¸¸½ø³ÌµÄËùÓнø³ÌÃèÊö·ûµÄÐÅÏ¢¾«È·¿½±´¹ýÀ´£¬ºÍ¸¸½ø³ÌÒ»Ñù£¨³ýÁ˽ø³ÌID²»Ò»ÑùÍ⣩£¬´úÂë¶Î¹²Ïí£¬Êý¾Ý¶ÎºÍ¶ÑÕ»¶Î¸´ÖÆ£¬ËùÓеļĴæÆ÷µÄֵȫ²¿¾«È·¿½±´£¬ÎļþÃèÊö·ûÒ²Ðí¾«È·¿½±´¡£

forkµÄ·µ»ØÖµ£¬forkÔÚ¸¸½ø³Ì¿Õ¼äÖзµ»Ø×Ó½ø³ÌµÄPID£¬ÔÚ×Ó½ø³Ì¿Õ¼äÖзµ»Ø0¡£
ÎÄÕÂÆÀÂÛ

¹²ÓÐ 1 ÌõÆÀÂÛ

  1. shell2010 ÓÚ 2008-05-25 10:35:23·¢±í:

    ÒýÓÃ:
    Ô­ÌûÓÉ lixceo ÓÚ 2008-5-23 12:35 ·¢±í
    Ô­´´£ºlobbve223

    //fork() ·µ»ØµÄdefaultÖµÒâζ×ÅÄãÕýÔÚ¸¸½ø³ÌÖУ¬·µ»ØÖµÊÇ×Ó½ø³ÌµÄ PID ¡£ÕâÊǵõ½×Ó½ø³Ì PID µÄΨһ·½·¨


    ÔÚ case 0: Àï getpid() ²»Ò²¿ÉÒÔ»ñÈ¡×Ó½ø³ÌµÄ PID ô£¿Õâ²»ÊÇΨһ·½·¨°É£¿