【发布时间】:2016-10-25 17:27:12
【问题描述】:
我必须开发自己的 C 函数system。为此,我使用调用系统fork 创建一个子进程,它必须执行给system 的命令,调用exec。
我写的似乎工作正常(它编译和执行没有任何错误)。
问题与我的函数system 的返回有关(在我的代码中称为mySystem)。例如,在我的子进程中,如果我给 exec 一个不存在的 shell(后者返回 -1),我的子进程会以 -1 的退出代码停止,因为我告诉它这样做。但是:我的父进程通过wait(&status) 检索此退出代码,返回... 255 而不是 -1!
我不明白为什么。我注意在mySystem的返回中使用宏WEXISTATUS。
您能帮我知道为什么我的父进程不返回 -1(其子进程的退出代码)吗?提前谢谢你。
我的src(有很多cmets):
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
pid_t pid;
int mySystem(char*);
int main(int argc, char* argv[]) {
int result = mySystem("ls");
fprintf(stdout, "%i", result);
return 0;
}
int mySystem(char* command) {
pid = fork();
if(pid == -1) {
perror("Fork");
return -1; // An error occurred => return -1
} else if (pid == 0) { // The child process will do the following
execl("BLABLABLABLA MAUVAIS SHELL BLABLABLAA", "sh", "-c", command, NULL); // If this call doesn't fail, the following lines are not read
perror("Exec"); // If (and only if) execl couldn't be called (bad shell's path, etc.)...
exit(-1); // ..., we stop the child process and this one has an exit code equaled to -1
}
/*
* NOW, the child process ended because... :
* 1. Either because of our "exit(-1)" after the "perror" (our source-code)
* 2. OR because of an "exit(-1") of the command passed into the execl (source-code of the execl's command)
* 3. OR because of the "exit(0)" of the command passed into the execl (source-code of the execl's command)
*/
// The parent process will execute the following lines (child process ended)
int status = -1;
if(wait(&status) == -1) { // We store into the var 'status' the exit code of the child process : -1 or 0
perror("Wait"); // Note that because we have only one process child, we don't need to do : while(wait(&status) > 0) {;;}
return -1;
}
return WEXITSTATUS(status); // Our function mySystem returns this exit code
}
【问题讨论】:
-
文档是怎么说的?您在文档中没有理解什么?
-
啊,我再次阅读了文档,我认为我的错误必然是“这由最低有效的 8 位组成”......嗯,我无法返回正值。我会把回报投给
signed char。 -
顺便说一句,POSIX specifies shell 中“找不到程序”的退出代码为 127。