Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 7 Apr 1999 17:38:51 -0700 (PDT)
From:      Matthew Dillon <dillon@apollo.backplane.com>
To:        Simon Shapiro <shimon@simon-shapiro.org>
Cc:        freebsd-hackers@FreeBSD.ORG
Subject:   Re: wait4 - Proof I am stupid
Message-ID:  <199904080038.RAA07199@apollo.backplane.com>
References:   <XFMail.990407203255.shimon@simon-shapiro.org>

next in thread | previous in thread | raw e-mail | index | archive | help
:Hi Y'll,
:
:Please bear with me:
:...
:
:        switch (y = wait4((-1)* my_pgid, &z, NULL)) {
:...
:
:Question:  Why?  Obviously I am doing something wrong, but what?

    wait4 takes four arguments, not three.  man wait4.

    I also strongly suggest compiling with -Wall so you get appropriate
    errors when you forget to include the right header files.

    Also, your code flow for fork() is dangerous, even if it is only 
    demonstration code :-).  When you fork, the child should never fall 
    through into the parents code... it should _exit(0) 
    ( note the underscore ) before then.  You also need to make sure that
    any FILE buffers are flushed before you fork to avoid a double-flush
    ( where both parent and child flush the same buffered data in FILEs ).


    fflush(stdout);	/* prevent double flush from occuring in child */
    fflush(stderr);	/* prevent double flush from occuring in child */
    if ((pid = fork()) == 0) {
	/* child does something */
	_exit(0);
    }
    if (pid == (pid_t)-1) {
	/* fork error occured */
	exit(1);
    }
    /* parent continues execution */

    To wait for the child to exit with wait4():

	if (wait4(pid, NULL, 0, NULL) < 0) {
	    /* something unexpected happened */
	}
	/* wait complete.  child is gone */

    If you are interested in using a more portable function, look at 
    waitpid() rather then wait4().

	if (waitpid(pid, NULL, 0) < 0) {
	    /* something unexpected happened */
	}
	/* wait complete.  child is gone */

    If you want the return code:

	int status;
	int return_code;

	if (waitpid(pid, &status, 0) < 0) {
	    /* something unexpected happened */
	}
	return_code = WEXITSTATUS(status);

    See 'man waitpid'.

					-Matt
					Matthew Dillon 
					<dillon@backplane.com>

:Note:  The ``code'' above is illutration only...
:
:Sincerely Yours,                 Shimon@Simon-Shapiro.ORG
:                                             770.265.7340
:Simon Shapiro




To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?199904080038.RAA07199>