简体   繁体   English

第一次调用perror()成功,第二次返回非法搜索?

[英]calling perror() first time success, second time returns ILLEGAL SEEK?

I'm doing a system call to change the current directory in C++ program and for some reason first call returns success on the PERROR IN THE ELSE and the second one returns Illegal seek on the PERROR IN THE ELSE(using same command and both call to the functions will direct to the else clause). 我正在进行系统调用以更改C ++程序中的当前目录,由于某种原因,第一次调用会在PERROR IN ELSE上返回成功,而第二次调用会在PERROR IN ELSE上返回非法查找(使用相同的命令,并且都调用函数将直接指向else子句)。 Any idea why? 知道为什么吗? Thanks. 谢谢。 I appreciate you guys' help! 我感谢你们的帮助!

void changedir(cmd_t& command, int numArg)
{
  char buffer[MAXCHAR];
  if (numArg == 1){
    chdir(getenv("HOME"));
    perror("chdir");
    getcwd(buffer, MAXCHAR);
    cout << buffer << endl;

  } else {
    chdir(command.argv[1]);
    perror("chdir");
    getcwd(buffer, MAXCHAR);
    cout << buffer << endl;

  }
}

Don't call perror if no error has occurred. 如果没有发生错误,请不要调用perror It will give you meaningless output. 它将给您毫无意义的输出。

In general, the value of errno is undefined after a system/library call, unless that call documents that it sets it to a specific value. 通常,在系统/库调用之后, errno的值是不确定的,除非该调用说明将其设置为特定值。 This generally only happens when the call failed and the function signaled that through its return value. 通常仅在调用失败并且函数通过其返回值发出信号时才会发生这种情况。

In your specific case, don't call perror unless chdir returned -1 . 在您的特定情况下,除非chdir返回-1 ,否则不要调用perror

On Linux, chdir will raise an EFAULT error if you give it a NULL pointer, but that's not mandated in POSIX ( chdir ), so better check the result of getenv before calling chdir (same thing for your command.argv[i] if that can potentially return a null pointer). 在Linux上,如果您给NULL指针指定chdir则会引发EFAULT错误,但这不是POSIX( chdir )所chdir ,因此最好在调用chdir之前检查getenv的结果(与command.argv[i]相同)可能会返回空指针)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM