Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
execl正在成功-但是正在调用exit(1)_C_Error Handling_Exec - Fatal编程技术网

execl正在成功-但是正在调用exit(1)

execl正在成功-但是正在调用exit(1),c,error-handling,exec,C,Error Handling,Exec,我试图更好地理解exec()-因此我在testing.c #包括 #包括 #包括 #包括 #包括 int main(int argc,字符**argv) { 如果(argc

我试图更好地理解exec()-因此我在
testing.c


#包括
#包括
#包括
#包括
#包括
int main(int argc,字符**argv)
{
如果(argc<2){
fprintf(stderr,“Error::应为参数!\n”);
出口(-1);
}
pid_t pid;
pid=fork();
如果(pid==0){
execlp(“./测试”,“测试”,空);
fprintf(stderr,“我想去这里…\n”);
出口(-1);
}
等待(空);
printf(“父项和子项完成\n”);
返回0;
}
下面的块是我使用
/测试一个
执行后的输出:

Error:: Expecting an Argument!
Parent and child done
在阅读
exec()
的工作原理时,我希望在调用
execlp
后能够
fprintf
,因为它应该返回-1,我想知道我是否需要设置一个errno或什么,或者更明确地抛出一些东西,以便
execlp
重新编码错误?

输出:

Error:: Expecting an Argument!
Parent and child done
来自

(first line) child process tries to run but no command line parameter.  
(second line) parent process finishes

如果
execlp
函数成功启动给定程序,则它不会返回。当前程序映像将替换为新程序的程序映像。因此,即使新程序以状态-1退出,它仍然不会返回到调用
execlp
的程序

如果要获取子进程的退出状态,请将
int
的地址传递到
wait
并读取:

int main(int argc, char ** argv)
{
  if(argc < 2) {
    fprintf(stderr,"Error:: Expecting an Argument!\n");
    exit(-1);
  }
  pid_t pid;
  pid = fork();
  if (pid == -1 {
      perror("fork failed");
      exit(-1);
  } else if (pid == 0) {
    execlp("./testing","testing",NULL);
    perror("execlp failed");
    exit(-1);
  }
  int status;
  wait(&status);
  printf("child exit status: %d\n", WEXITSTATUS(status));
  printf("Parent and child done\n");
  return 0;
}
int main(int argc,char**argv)
{
如果(argc<2){
fprintf(stderr,“Error::应为参数!\n”);
出口(-1);
}
pid_t pid;
pid=fork();
如果(pid==-1{
perror(“fork失败”);
出口(-1);
}否则如果(pid==0){
execlp(“./测试”,“测试”,空);
perror(“execlp失败”);
出口(-1);
}
智力状态;
等待(&状态);
printf(“子退出状态:%d\n”,WEXITSTATUS(状态));
printf(“父项和子项完成\n”);
返回0;
}

man 3 exec
:返回值exec()函数仅在发生错误时返回。返回值为-1,并且errno被设置为指示错误。是什么使您认为
execlp
调用失败?关于:
error::需要参数!
此消息是因为您没有提供命令行参数,而代码需要该参数代码没有编译!它缺少以下
#include
语句:#include#include#include#include#include当包含命令行参数时,输出是:
我想转到这里…父项和子项都完成了
是的,我理解-但我在想
fprintf(stderr,“我想转到这里…\n”);
也应该运行,因为子进程正在返回-1一个重要的细节。除非操作失败,
exec*()
函数不会返回