1

I Experimented the system function call. It is used to execute the command with in the program. The man page contains the following information about the return value of system.

RETURN VALUE

The value returned is -1 on error (e.g.  fork(2) failed), and the return status of the command otherwise.

As per the man page reference, I checked the following program.

Program:

#include<stdio.h>
#include<unistd.h>
int main()
{   
    printf("System returns: %d\n",system("ls a"));
}

Output:

$ ./a.out 
ls: cannot access a: No such file or directory
System returns: 512
$ ls a
ls: cannot access a: No such file or directory
mohanraj@ltsp63:~/Advanced_Unix/Chapter8/check$ echo $?
2
$ 

The above output shows that, return value of system function is 512 and the exit status of ls a command is 2. As per the reference, I expect the return value of system function is equal to exit status of the ls command. But the value becomes different. Why?

mohangraj
  • 9,842
  • 19
  • 59
  • 94
  • 2
    You probably want to use [`WEXITSTATUS`](http://man7.org/linux/man-pages/man2/wait.2.html) on that value (subject to appropriate conditions). – Kerrek SB Oct 14 '15 at 09:37
  • So, Here how can I get the real exit status of command which is passed to system function. – mohangraj Oct 14 '15 at 09:42
  • Read the linked document starting at "If status is not NULL," about half-way down. – Kerrek SB Oct 14 '15 at 09:45

2 Answers2

4

You forgot to read the whole section.

[T]he return value is a "wait status" that can be examined using the macros described in waitpid(2). (i.e., WIFEXITED() WEXITSTATUS() and so on).

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

The return value is the exit status of the shell, see sh(1), bash(1) or whatever you have configured in SHELL environment variable. By the way, the shell usually returns the last command executed exit value, but that can not be the case if you have hit the Ctrl-C key or sent a signal to the process. Check in the manual page for the exit value of the shell on these cases.

Luis Colorado
  • 10,974
  • 1
  • 16
  • 31