为什么当我在 c 中的函数内执行此代码时
int Pandoc(char *file)
{
//printf("Pandoc is trying to convert the file...\n");
// Forking
pid_t pid;
pid = fork();
if (pid == -1)
{
perror("Fork Error");
}
// child process because return value zero
else if (pid == 0)
{
//printf("Hello from Child!\n");
// Pandoc will run here.
//calling pandoc
// argv array for: ls -l
// Just like in main, the argv array must be NULL terminated.
// try to run ./a.out -x -y, it will work
char *output = replaceWord(file, ".md", ".html");
//checking if the file exists
char *ls_args[] = {"pandoc", file, "-o", output, NULL};
// ^
// use the name ls
// rather than the
// path to /bin/ls
// Little explaination
// The primary difference between execv and execvp is that with execv you have to provide the full path to the binary file (i.e., the program).
// With execvp, you do not need to specify the full path because execvp will search the local environment variable PATH for the executable.
if(file_exist(output)){execvp(ls_args[0], ls_args);}
else
{
//Error Handeler
fprintf(stdout, "pandoc should failed with exit 42\n");
exit(42);
printf( "hello\n");
}
}
return 0;
}
我得到的返回值是 0?
编辑: 所以这里我把main的返回值改成了5。 我上面的函数的退出值是 42(我不知道为什么) 它给了我 5 作为输出..不知道发生了什么。 我应该提到我在代码中使用了 fork() ..也许这就是原因。
我认为我的退出关闭了子进程,但主进程仍在继续..所以这就是为什么它给我主进程内部的返回值而不是退出进程的原因。
最佳答案
您的子进程以异常值退出,但您的主进程始终以 0 退出,这就是决定 $?
的原因。
如果您希望 $?
成为子进程的退出值,则必须使用 wait()
来获取它,检索子进程的退出代码,然后然后退出你的主进程。
关于c - exit(1) 没有给我 1 作为退出值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60583761/