c WEXITSTATUS()以255退出

时间:2016-03-10 21:04:14

标签: c exec

执行此片段时,我收到信息&#34;退出值255&#34;。我通过键盘接收命令,我知道字符串是正确的。当我收到错误消息时,程序不显示(例如)键盘接收到的ls -l <​​/ p>

    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);
        }

谢谢大家! 标记

1 个答案:

答案 0 :(得分: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)会产生退出结果0xaaaaaa;只有较低的几(8)位用于实际的退出值;较高的 aaaaaa 位用于退出的原因,等等。 - &GT;&GT;在WEXITSTATUS()中查看<sys/wait.h>和朋友的定义。