system()的返回值不是执行程序的返回值

我想执行一个可执行文件,其main()使用system()返回2。 这就是我所做的

 #include  #include  int main(int argc, char *agrv[]) { char command[7]; strcpy(command, "./test1"); printf("The return value: %d\n", system(command)); return 0; } 

test1

 #include  int main(void) { printf("test1 has been executed and its return value is 2\n"); return 2; } 

这就是我得到的

 test1 has been executed and its return value is 2 The return value: 512 

我的问题是为什么我得到512

系统的返回值实际上是POSIX下waitpid()的返回值。

status实际上嵌入了很多信息:

从系统(3)手册页:

以下宏可用于测试进程退出的方式。 前三个宏中的一个将评估为非零(真)值:

WIFEXITED(status)

如果通过调用_exit(2)或exit(3)正常终止进程,则为True

WIFSIGNALED(status)

如果由于收到信号而终止进程,则为True

WIFSTOPPED(status)

如果进程尚未终止,但已停止并可以重新启动,则为True
仅当等待调用指定了WUNTRACED选项或正在跟踪子进程时,此宏才可以为true(请参阅ptrace(2))。

根据这些宏的值,以下宏将生成有关子进程的其余状态信息:

WEXITSTATUS(status)

如果WIFEXITED(status)true ,则计算子项传递给_exit(2)或exit(3)的参数的低8位。

WTERMSIG(status)

如果WIFSIGNALED(status)true ,则计算导致进程终止的信号编号。

WCOREDUMP(status)

如果WIFSIGNALED(status)true ,则如果进程终止伴随着在收到信号时创建包含进程映像的核心文件,则计算结果为true。

WSTOPSIG(status)

如果WIFSTOPPED(status)true ,则计算导致进程停止的信号编号。

 #include  #include  #include  int main(int argc, char *argv[]) { int status; char command[PATH_MAX]; /* PATH_MAX is defined in sys/syslimits.h, included by limits.h */ strcpy(command, "./test1"); status = system(command); if ( WIFEXITED(status) ) { printf("The return value: %d\n", WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { printf("The program exited because of signal (signal no:%d)\n", WTERMSIG(status)); } return 0; } 

引用man 3 system

错误时返回的值为-1 (例如fork (2)失败),否则返回命令的返回状态。 后一种返回状态采用wait (2)中指定的格式。 因此,命令的退出代码将是WEXITSTATUS(status)

man 2 wait显示其他信息被打包到system (3)返回的status

  • 512表示程序退出,退出状态为2。
  • 2意味着程序被信号2(SIGINT)杀死。

请注意,由于尾随NUL,字符串./test1需要8个字符。 你的strcpycommand之外破坏了一些记忆。 固定:

 char command[8]; strcpy(command, "./test1"); 

当然,没有理由首先制作副本。

 const char* command = "./test1"; system(command) 

甚至

 system("./test1") 

事实上,这是未定义的行为。 command只保存7个字符,但字符串"./test1"有8个,包括空终止符。 您需要增加command的大小,或者直接使用文字字符串调用systemsystem("./test1")