(I'm developing a simple expect-like program.)
For example I have a program prog1.c
which fork()
and exec()
another program prog2
. When prog2
is killed by a signal (e.g. SIGPIPE
), prog1
can get its exit state with waitpid()
, WIFSIGNALED()
and WTERMSIG()
. Then prog1
would pass the exit state to prog1
's caller (a shell, like Bash or Ksh93) and I want to make it look like it's the shell that's calling prog2
so I want the shell to get the exact exit state of prog2
.
One way I can think of is that prog1
kills itself with the signal which killed prog2
but this sounds a bit weird so I want to know if there is other better way to do this.
Converting comments to answer.
If you want the reported status to be exact (signal status too), you'll have to exactly what you propose:
int status;
int corpse = wait(&status);
if (WIFSIGNALED(status))
kill(getpid(), TERMSIG(status));
else
exit(WEXITSTATUS(status));
Note that Bash reports death of children by signal by exiting normally with 128 + signal_number
. You might still have problems with core dumps. And you might need to handle some signals — job control signals, for example — a bit differently.
I only deal with scenarios where the child exits so would not handle things like WIFSTOPPED or WIFCONTINUED. Core dump is indeed something I have to think. Not sure if a C program can decide whether or not to dump a core but still be able to tell the caller that it's SIGSEGVed.
There are sometimes o/s specific interfaces to control core dump. For example, POSIX provides getrlimit()
and setrlimit()
which can limit the size of a core dump to 0, prevents core dumps. If the signal originally gave a core dump in the grandchild process, it probably will for the child process too -- but that could be a problem because the child's core overwrites the grandchild's core, leaving you without the relevant information. I'm not sure the extent to which you need to worry about that, or to which you can handle it with o/s-specific mechanisms. I don't know whether you get the 'core dumped' bit set even if the core was not created; probably not.