If I run the following code segment
pid_t p;
int status = 0;
p = fork();
if (p < 0)
report_error();
if (p == 0) // child
{
execlp("true", "true", 0);
_exit(127); // we should not get here
}
else
{
waitpid(p, &status, 0);
if(WIFEXITED(status))
printf("Exited with code %d", WEXITSTATUS(status));
}
I don't get anything printed because it seems like WIFEXITED evaluates to false. I suspect this is because "true" isn't a command per se and doesn't "exit" the child process?
Can I still rely on WEXITSTATUS(status)
even if it didn't "exit?" If I were to execlp("false", "false", 0);
instead, is it guaranteed that WEXITSTATUS(status)
is 1? It seems to be true so far, but I'd just like to confirm that this isn't just a coincidence.
This (a slight clean up):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main (int argc, char **argv)
{
pid_t p;
int status = 0;
p = fork ();
if (p < 0)
{
perror ("fork failed");
}
else if (p == 0) // child
{
execlp ("true", "true", NULL);
_exit (127); // we should not get here
}
else
{
waitpid (p, &status, 0);
if (WIFEXITED (status))
printf ("Exited with code %d\n", WEXITSTATUS (status));
}
}
prints
Exited with code 0
If I change both instances of true
to false
, it prints
Exited with code 1
I suspect the problem is thus in the code you haven't shown (e.g. any main
) or because your system for some reason doesn't have /bin/true
:
$ ls -la /bin/true
-rwxr-xr-x 1 root root 27168 Mar 24 2014 /bin/true
(why it takes 27168 bytes to return exit code 0 I don't know)
I tested this on the Mac on OS-X 10.9.5 too:
nimrod:~ amb$ cc --version
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix
nimrod:~ amb$ uname -a
Darwin nimrod.local 13.4.0 Darwin Kernel Version 13.4.0: Sun Aug 17 19:50:11 PDT 2014; root:xnu-2422.115.4~1/RELEASE_X86_64 x86_64
nimrod:~ amb$ which true
/usr/bin/true
nimrod:~ amb$ ls -la /usr/bin/true
-rwxr-xr-x 1 root wheel 13808 18 Feb 2014 /usr/bin/true