ºÜ¶à×ÊÁ϶¼ÓÐÒ»¸ö˵·¨£¬×Ó½ø³Ì¿ÉÒÔÓÃexit()É趨Í˳öÂë,Ò»°ãÓÃ0±íʾÕý³£Í˳ö£¬ÆäËûÖµ±íʾ·ÇÕý³£Í˳ö¡£µ«²âÊÔʱ¾ÍËãʹÓÃÁËÆäËûÖµ£¬¸¸½ø³Ìwait()ºóÓÃWIFEXITED(status);ÅжÏÆäÍ˳öÂ룬½á¹û»¹ÊÇÒ»¸öÕæÖµ¡£ºóÀ´²ÅÏëÇå³þ£¬Ç°Ãæ˵·¨ÖеķÇÕý³£Í˳öÊÇÖ¸³ÌÐò±¾ÉíÔËÐгö´í£¬ÕâÖÖ³ö´í¾Í¿ÉÒÔÖ¸¶¨¶ÔÓ¦µÄÍ˳öÂë¡£»¹ÓÐÁíÍâÒ»ÖÖÒì³£Í˳ö£¬ÄǾÍÊdzÌÐò±»ÍⲿÐźŴò¶Ï£¬ÕâʱÔÙÈ¥ÅжÏ×Ó½ø³ÌµÄÍ˳öÂëʱ·¢ÏÖ WIFEXITED(status);µÃµ½0Öµ¡£ËùÒÔҪעÒâÕâÀï¶ÔÓÚ´íÎóµÄÃèÊö¡£
//ÕâÀï²âÊÔ½ø³Ì±»ÖжϻòÕß±»É±ËÀºóÆäÍ˳öÇé¿ö£¬Õâ¸öÍ˳ö²ÅÊÇÕæÕýµÄ·ÇÕý³£Í˳ö£¬ËùÒÔÕâʱÓÃWIFEXITED(status)
//ÅжϽá¹û¾Í»áʱһ¸ö 0 Öµ £¬É±ËÀ¸Ã½ø³ÌµÄ·½·¨ ÊÇ kill -9 ½ø³Ìid
//±Ê¼ÇÖÐ˵µÄʹÓ÷ÇÕý³£µÄÍ˳öÂ룬ÊÇÖ¸½ø³Ì±¾Éí´íÎóµÄ·µ»Ø£¨½ø³ÌÒ²ÊÇ˳ÀûÔËÐеģ©
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <error.h>
main()
{
//´´½¨×Ó½ø³Ì
pid_t f_pid = fork();
//´´½¨Ê§°Ü
if(f_pid < 0)
{
perror("fork");
return -1;
}
//·µ»Ø0±íʾ×Ó½ø³Ì
if( f_pid == 0 )
{
//»ñÈ¡±¾½ø³Ìid
pid_t pid = getpid();
printf("chil exit pid = %d\n",pid);
while(1);
//ÉèÖÃÍ˳öÂë
exit(EXIT_SUCCESS);
//exit(EXIT_FAILURE);
}
//·µ»Ø´óÓÚ0£¬±íʾ¸¸½ø³Ì£¬²¢ÇÒ·µ»Ø×Ó½ø³Ìid
else
{
//ÈÃ×Ó½ø³ÌÏÈÔËÐÐ
sleep(2);
//±£´æ×Ó½ø³ÌµÄÍ˳ö״̬
int status;
//Ö¸¶¨µÈ´ýµÄ×Ó½ø³Ì ºóÃæµÄ²ÎÊý·Ö±ð±íʾ ×Ó½ø³Ìid£¬±£´æ״̬µÄµØÖ·£¬²»×èÈûµÄµÈ´ý
pid_t chilpid = waitpid(f_pid, &status, 0);
printf("waiting for %d \n",chilpid);
int ret;//ÅжÏ×Ó½ø³ÌµÄÍ˳öÇé¿ö
//Õý³£Í˳ö·µ»Ø·Ç¸ºÊý£¬·ÇÕý³£Í˳ö·µ»Ø0
ret = WIFEXITED(status);
printf("WIFEXITED---ret= %d \n",ret);
//»ñÈ¡×Ó½ø³ÌÍ˳ö״̬Âë
ret = WEXITSTATUS(status);
printf("WEXITSTATUS---ret= %d \n",ret);
//while(1);
}
}