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 to catch stderr from a failed exec command?

When failing to launch an exec command – I can only get a bad return code from the exec – how can I also get the stderr?

#include <stdio.h>
#include <unistd.h>

int main(){
    char* argv[] = {"bla", NULL};
    execvp(argv[0], argv);
    printf("exec failed\n");
    return 0;
}

In this snippet the printf is only reached if the execvp breaks – which in my case it does. I’m interested in getting the output of the shell for trying to run bla:

Command 'bla' not found, did you mean:

  command 'tla' from deb tla (1.3.5+dfsg1-2build1)
  command 'bwa' from deb bwa (0.7.17-4)
  command 'bls' from deb bacula-sd (9.4.2-2ubuntu5)

Try: sudo apt install <deb name>

How can I find it? tried playing with errno but didn’t find the data I’m looking for

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

errno try:

#include <errno.h>
#include <stdio.h>
#include <unistd.h>

int main() {
  char* argv[] = {"bla", NULL};
  execvp(argv[0], argv);
  printf("exec failed\n %d", errno);
  return 0;
}

returns 2 – but no info.

2 is " 2 ENOENT No such file or directory" – but I still want Bash‘s stderr

>Solution :

You need to #include <errno.h>, you can also use perror() to get more information about the error:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int main(void)
{
    char* argv[] = {"bla", NULL};

    execvp(argv[0], argv);
    perror("execvp");
    fprintf(stderr, "errno: %d\n", errno);
    exit(EXIT_FAILURE);
}

Output:

execvp: No such file or directory
errno: 2
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