【问题标题】:How to re-develop the sys-function "system()" cleanly?如何干净地重新开发系统功能“system()”?
【发布时间】: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。

标签: c process exit-code


【解决方案1】:

看下图:

其中 2 个块中的每一个都是 8 位(总共 16 位)。 现在你传递exit(-1),它使用8位二进制是:11111111(两个补码)这就是你使用WEXITSTATUS(status)得到255的原因。

另一个要明确的例子:假设调用exit(-6),二进制二补码中的-6是11111010,对应于250,如果你让你的程序运行你会在stdout上看到250。

【讨论】:

  • 非常感谢。 “状态”是“主要返回”和“退出”值吗?我想是这样 ;因此,错误代码是什么?是“错误”吗?我认为它也可能是“主要返回”或“退出”值。
  • 不,exit() 调用没有设置 errno 值,我建议你寻找 errno stackoverflow.com/questions/11699596/how-to-set-errno-value
  • 谢谢,我已经知道了。我只是不清楚用于流程的词汇(图像中的状态和错误代码)。我认为“状态”是进程的一个(所以不是返回主/退出的值)和错误代码,errno。但事实并非如此。
猜你喜欢
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多