Return value of System Function [duplicate]

2019-08-10 05:51发布

问题:

This question already has an answer here:

  • system() call is returning wrong value in C 2 answers

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?

回答1:

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).



回答2:

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.