我必须开发自己的C函数system。为此,我使用调用系统创建一个子进程,它必须执行给fork的命令,调用system
我所写的似乎工作得很好(它编译和执行没有任何错误)。
问题涉及函数的返回(在我的代码中称为exec)。例如,在我的子进程中,如果我给一个不存在的shell提供了system(后者返回- 1),我的子进程用1的退出代码停止,因为我告诉它这样做。但是,我的父进程,由于一个mySystem,检索这个退出代码,返回…255而不是-1!
我不明白为什么。我注意在exec的返回中使用宏WEXISTATUS。
你能帮我知道为什么我的母进程不返回- 1(它的子进程的退出代码)吗?提前谢谢你。
我的src(有很多评论):

#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
}

最佳答案

请看下图:
c - 如何干净地重新开发sys-function“system()”?-LMLPHP
其中两个块中的每一个都是8位(所以总共16位)。
现在您传递exit(-1)它在二进制中使用8位是:1111111(两个补码),这就是为什么您使用WEXITSTATUS(status)得到255。
另一个需要说明的例子是:假设调用exit(-6),二进制二补中的-6是11111010,对应于250,如果您运行程序,您将看到250打印在stdout上。

关于c - 如何干净地重新开发sys-function“system()”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37990593/

10-12 22:14
查看更多