Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I Exit a Process if a Child Fails?

The program I’m working with requires a secondary executable to run (for asset compression). For error handling reasons, I need the return value of the child process. According to the system man page,

If all system calls succeed, then the return value is the termination status of the child shell used to execute [the] command. (The termination status of a shell is the termination status of the last command it executes.)

According to this, my system call’s return state should be the called process’s return value. But it doesn’t seem to be. Instead, when the Generator returns EXIT_FAILURE, the program receives an EXIT_SUCCESS, or 0. Am I misunderstanding something?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code is below.

// Checks to see if the generator still exists using access().
bool asset_generator_availability = CheckAssetGenerator();

if (!asset_generator_availability) LogMessage("Assets already generated.");
else
{
    LogWarning(
        "Assets still uncompressed and unformatted. Running the Generator.");

    u8 generator_state = system("./AssetGenerator && rm AssetGenerator");
    // Here is the problem line.
    if (generator_state == EXIT_FAILURE) exit(EXIT_FAILURE);
}

>Solution :

This issue is occurring because when system successfully runs the called process it doesn’t return the direct return value of the process run. It instead returns a "wait status" that can be examined using the macros described in waitpid(2). (i.e., WIFEXITED(), WEXITSTATUS(), and so on).
The manual pages have more detail on this matter but for your code you could use WIFEXITED and WEXITSTATUS as follows:

if (WIFEXITED(generator_state) && WEXITSTATUS(generator_state) == EXIT_FAILURE)
{
exit(EXIT_FAILURE);
}

In this code WIFEXITED checks that the child exited normally, and WEXITSTATUS checks the exit status of the child. Hope that helps!

Edit: Below are the manual pages for system and wait.
https://man7.org/linux/man-pages/man3/system.3.html
https://man7.org/linux/man-pages/man2/waitpid.2.html

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading