c WEXITSTATUS() 以 255 退出

c WEXITSTATUS() exited with 255

当执行这一段 os 代码时,我收到信息 "Exited with value 255"。我通过键盘接收命令,并且我知道字符串是正确的。当我收到错误消息时,程序不显示(例如)键盘收到的 ls -l

    printf("Command? ");
    scanf(" %99[^\n]", str);

    p = fork(); 
        if(p > 0 ){   //Dad wait for the child
            wait(&status);
            if(WIFEXITED(status)){
                printf("%d\n",WEXITSTATUS(status));
            }   
        }else{      //Child execute the execlp  
            execlp(str, str,NULL);
            exit(-1);
        }

谢谢大家! 马克

execlp() 期望参数被分开;您的字符串输入 ls -l 不是有效的现有可执行程序:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

char *args[] = { "ls", "-l" };
// int main (int argc, char **argv)
int main (void)
{
int p;
int status;

p = fork();
if(p > 0 ){   //Dad wait for the child
     wait(&status);
     if (WIFEXITED(status)){
         printf("%d\n", WEXITSTATUS(status));
        }
     }else{      //Child execute the execlp  
         execlp(args[0], args[0], args[1] ,NULL);
         exit (-1);
     }

exit (0);
}

另请注意,exit(-1)(除了无效:您应该使用 EXIT_FAILURE)会产生 0xaaaaaaFF 的退出结果;只有较低的几 (8) 位用于实际退出值;较高的 aaaaaa 位用于退出的原因,等等。 -->> 在<sys/wait.h>.

中查看WEXITSTATUS()和朋友的定义