Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to correctly interpret return values from system() in c program

Tags:

c

linux

OS: linux

I am unable to interpret the output from the following program:

#include <stdlib.h>
#include <sys/mount.h>
#include <errno.h> 
#include <stdio.h>

*****updated code*****

 void mount_sys() {
    if (0 != mount("none", "/sys", "sysfs", 0, ""))
 {
           /* handle error */
    }
    }


int 
main()
{

int a,b, err;
FILE *file;
err=putenv("PATH=/bin");
printf("putenv return value =%d\n",err);
mount_sys();
;
  err=system("echo 47 > /sys/class/gpio/export");
  if (err == 0) {
    printf("system called good");
  } else {
    perror("Error");
  }

  err=system("echo out > /sys/class/gpio/gpio47/direction");

  if (err == 0) {
    printf("system called good");
  } else {
    perror("Error");
  }

  err=system("echo 1 > /sys/class/gpio/gpio47/value");

  if (err == 0) {
    printf("system called good");
  } else {
    perror("Error");
  }

  return 0;
}

Output

Error: Success
Error: Success
Error: Success

If all the system calls were successful I should have got system called good messages three times.

But it looks like it is failing. But then why the errors being printed using perror() are Success ?

like image 218
Uzair Avatar asked Apr 16 '26 17:04

Uzair


2 Answers

The correct way to handle a call to system() shall be:

#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h> /* For WEXITSTATUS */

int main(void)
{
  int result = EXIT_SUCCESS; /* Be optimistic. */
  char cmd[] = "mycommand";

  int status = system(cmd);
  if (-1 == status)
  {
    perror("system() failed internally");
    result = EXIT_FAILURE;
  }
  else
  {
    fprintf(stderr, "'%s' returned %d.\n", cmd, WEXITSTATUS(status));
  }

  return result;
}
like image 85
alk Avatar answered Apr 19 '26 07:04

alk


The value returned by system() can be one of two things:

the exit status of the shell command, or

-1 (indicating that the fork() system call itself failed)

perror() is only relevant in the second case. As others have suggested, print out the value of err instead of just relying on perror().

---- update --- The return value includes both the exit status of the process (top 8 bits) and the signal # that killed the process (if any, lower 8 bits). 32512 == 127 << 8, so the shell exit code was 127.

According to this: 127 Return code from $?

that return code indicates that the command you're trying to run (echo) is not in the PATH of your shell

like image 28
David Gelhar Avatar answered Apr 19 '26 09:04

David Gelhar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!