簡體   English   中英

execvp():沒有這樣的文件或目錄?

[英]execvp(): no such file or directory?

出於某種原因, execvp()在我的PATH文件中找不到包含/ bin的命令(如ls,pwd等)。 由於我有ls的自定義終端別名,我正在使用pwd等進行測試(以及一台新的Linux機器),但我不斷得到這個輸出:

gcc main.c
./a.out

What would you like to do?
ls
arg[0]: ls

arg[1]: (null)
arg[2]: (null)
arg[3]: (null)
arg[4]: (null)
arg[5]: (null)
arg[6]: (null)
arg[7]: (null)
arg[8]: (null)
arg[9]: (null)
before exec
after exec
ERROR: No such file or directory

這是代碼:

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

/* 
Write a c program that runs a command line program with exactly one command line argument. It should work as follows:
Prompts the user for a program to run via the command line.
Reads in that line (using fgets) and parses it to be used by one of the exec functions.
Runs the command using exec
You do not need to fork off a separate process and wait, the purpose of this assignment is only to parse a single line of input and run a program once.
*/

int main() {
  printf("\nWhat would you like to do?\n");

  char* input = malloc( 100 ); //100 character string for input
  fgets(input, 100, stdin); //reads from stdin (terminal input "file")

  //parses command in input (max of 8 flags)
  int number_of_args = 10;

  char *args[number_of_args];

  //puts cmd && flags in args
  int i = 0;
  for(; i < number_of_args; i++) {
    args[i] = strsep( &input, " ");
    printf("arg[%i]: %s\n", i, args[i]);
  }
  args[number_of_args - 1] = 0; //last element for execvp must be NULL;
  //  printf("nullify final index -> args[%i] = %s\n", number_of_args - 1, args[number_of_args -1]);

  printf("before exec\n");
  int e = execvp( args[0], args);
  printf("after exec\n");
  if(e < 0)
    printf("ERROR: %s\n", strerror(errno));

  return 0;
}

編輯:認為包括我的PATH也是好的:

echo $PATH
/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

如果緩沖區中有可用空間, fgets()將讀取換行符。 所以當你輸入ls ,它實際上是ls\\n 顯然, execvp()找不到這樣的命令,它就失敗了。 因此,解決方案是刪除尾隨換行符(如果有)。

char *p = strchr(input, '\n');
if (p)  *p = 0;

您還應該使用argc進行參數處理(如果您通過main()的參數讀入命令和參數)而不是假設某些固定數字。 或者只是在strsep()第一次返回NULL時斷開循環。 從技術上講,當您打印所有這些空字符串時,您的代碼會調用未定義的行為

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM