Reputation: 119
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 ?
Upvotes: 3
Views: 782
Reputation: 70911
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;
}
Upvotes: 2
Reputation: 27900
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
Upvotes: 1