【问题标题】:C `execlp` falls even if the executable file exists即使可执行文件存在,C `execlp` 也会下降
【发布时间】:2013-12-29 14:26:06
【问题描述】:

我是 C 新手。我正在通过 Stevens & Rago 的书学习 UNIX。我有一个问题。早期的数字之一在我的实现中不起作用。

#include "apue.h"                                     
#include <sys/wait.h>                                 

int                                                   
main(void)                                            
{                                                     
  char buf[MAXLINE];                                  
  pid_t pid;                                          
  int status;                                         

  printf("%% ");                                      
  while (fgets(buf, MAXLINE, stdin) != NULL) {        
    if (buf[strlen(buf) - 1] == "\n")                 
      buf[strlen(buf) - 1] = 0;                       

    if ((pid = fork()) < 0) {                         
      err_sys("Fork error: %d");                      
    }                                                 
    else if ((pid == 0) && (access(buf, F_OK ) != 1)){ /* Here I have an extra check to ensure, that the binary exists. */
      execlp(buf, buf, (char *)0);                    
      err_ret("Couldn't execute: %s", buf);           
      exit(127);                                      
    }                                                 

    if ((pid = waitpid(pid, &status, 0)) < 0)         
      err_sys("waitpid error");                       
    printf("%% ");                                    
  }                                                   
  exit(0);                                            
}                                                     

当我启动程序时:

$ ./exec
% /bin/ls
Couldn't execute: /bin/ls
: No such file or directory

我有几个关于execlp(buf, buf, (char *)0);的问题:

为什么execlp 不能执行二进制文件?

int execlp(const char *file, const char *arg, ...);

为什么buf 通过了两次?如果第二个参数必须是二进制的参数。 找不到,是什么意思:(char *)0?这是什么指针?那里的零是什么?

【问题讨论】:

  • 如果你不认识空指针和类型转换,那么现在还不是你搞乱流程管理和其他东西的时候。首先学习 C 的基础知识。

标签: c binary executable system-calls


【解决方案1】:
Couldn't execute: /bin/ls
: No such file or directory

请注意,错误消息在新行上,但您尝试从输入中删除行尾字符。因此,您的移除似乎不起作用。

原因是:

if (buf[strlen(buf) - 1] == "\n")

您将字符 (buf[x]) 与字符串 ("\n") 进行比较,即指针。打开编译器的警告并仔细阅读。

试试这个:

if (buf[strlen(buf) - 1] == '\n')

execlp 的参数在its man page 中有描述:

按照惯例,第一个参数应该指向与正在执行的文件关联的文件名。

或者在 POSIX 中 here

(char *)0char* 类型的空指针。这里没有什么魔法,一个值为 0 的整数常量是一个空指针常量。但是由于execlp 是一个可变参数函数,因此强制转换是必要的——否则常量零将被视为int,它可能与指针的大小不同(并且空指针的内部表示可能不会与整数 0) 相同,导致未定义的行为。

【讨论】:

    【解决方案2】:

    你的代码是对的,我刚刚编译了除此之外。不要使用双引号(“),像这样在单引号中使用

    buf[strlen(buf) - 1] == '\n'
    

    也包括这个

    #include<stdio.h>
    #include<stdlib.h>
    
    #include<unistd.h>
    
    #include<string.h>
    

    【讨论】:

      猜你喜欢
      • 2017-11-08
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 2021-04-11
      • 2015-11-30
      相关资源
      最近更新 更多