我想执行一个可执行文件,其 main() 返回 2 使用system()
。
这就是我所做的
#include <stdio.h>
#include <string.h>
int main(int argc, char *agrv[])
{
char command[7];
strcpy(command, "./test1");
printf("The return value: %d\n", system(command));
return 0;
}
and test1
is
#include <stdio.h>
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
.
system的返回值实际上就是POSIX下waitpid()的返回值。
status
其实里面蕴藏着很多信息:
来自 system(3) 联机帮助页:
以下宏可用于测试退出方式
过程。前三个宏之一的计算结果为非零
(真实)值:
WIFEXITED(status)
True
如果进程通过调用 _exit(2) 或 exit(3) 正常终止。
WIFSIGNALED(status)
True
如果进程由于收到信号而终止。
WIFSTOPPED(status)
True
如果进程尚未终止,但已停止并可以重新启动。
仅当等待调用指定了该宏时,该宏才为真WUNTRACED
选项或者是否正在跟踪子进程(请参阅 ptrace(2))。
根据这些宏的值,以下宏会产生
有关子进程的剩余状态信息:
WEXITSTATUS(status)
If WIFEXITED(status)
is true
,计算结果为子级传递给 _exit(2) 或 exit(3) 的参数的低 8 位。
WTERMSIG(status)
If WIFSIGNALED(status)
is true
,计算出引起该事件的信号数量
终止进程。
WCOREDUMP(status)
If WIFSIGNALED(status)
is true
,如果进程的终止伴随着创建包含接收到信号时进程的映像的核心文件,则评估为 true。
WSTOPSIG(status)
If WIFSTOPPED(status)
is true
,计算导致进程停止的信号数量。
Solution
#include <stdio.h>
#include <string.h>
#include <limits.h>
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)