Portál AbcLinuxu, 12. května 2025 07:26
int ctenar(int client) { int pid=fork(); if (pid==0) { pid=getpid(); printf("Do knihovny vstoupil čtenář číslo %d\n",pid); char data[1000]; while (1) { read(client,data,sizeof(data)); if (!strncasecmp(data,"close",5)) { printf("Čtenář odešel\n"); close(client); client=0; int re=kill(pid,SIGSTOP); if(re==-1) { printf("Ukončení potomka se nepovedlo\n"); } else { printf("Potomek úspěšně ukončen\n"); } } } } else { return 0; } }Chtěl bych, aby po tom co klient zadá close se proces ukončil, ale nedaří se mi to. Buď mi proces zůstane, nebo se z něho stane zoombie. Co dělám špatně?
waitpid()
. Obvykle se tak děje v reakci na signál CHLD
.
int ctenar(int client) { int pid=fork(); if (pid==0) { pid=getpid(); printf("Do knihovny vstoupil čtenář číslo %d\n",pid); char data[1000]; while (1) { read(client,data,sizeof(data)); if (!strncasecmp(data,"close",5)) { printf("Čtenář odešel\n"); close(client); client=0; exit(0); } } } else { int status; int ret=waitpid(pid,&status,WNOHANG); if (ret==-1) { printf("Proces se nepodařilo ukončit\n"); } else if (ret == 0) { printf("Proces běží\n"); } else { printf("Proces úspěšně ukončen\n"); } return 0; } }
int ret=waitpid(pid,&status,WNOHANG);Přečti si v manuálu waitpid, co znamená flag WNOHANG a bude ti jasné proč.
waitpid()
dříve, než dostanete signál CHLD
.
POSIX.1-2001 specifies that if the disposition of SIGCHLD is set to SIG_IGN or the SA_NOCLDWAIT flag is set for SIGCHLD (see sigaction(2)), then children that terminate do not become zombies and a call to wait() or waitpid() will block until all children have terminated, and then fail with errno set to ECHILD.pokud je program kratky (co do trvani, tedy ne nejaky dlouhotrvajici process) tak se da vyuzit i toho, ze po skonceni rodice, se zombici prevedou na init kterej ceka ve waitu na jejich konec a tim se odstrani zombie. u delsiho programu, kde je potreba znat jak syn skoncil, je podle mne nejlepsi vyse navrhovane reseni.
V praxi je to ale trochu složitější:
POSIX.1-1990 disallowed setting the action for SIGCHLD to SIG_IGN. POSIX.1-2001 allows this possibility, so that ignoring SIGCHLD can be used to prevent the creation of zombies (see wait(2)). Nevertheless, the historical BSD and System V behaviours for ignoring SIGCHLD differ, so that the only completely portable method of ensuring that terminated children do not become zombies is to catch the SIGCHLD signal and perform a wait(2) or similar.
Bohužel se mi teď nepodařilo dohledat, od kdy se Linux chová podle novější specifikace.
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.