为什么当我在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(idk为何如此)它给了我5作为输出..不知道发生了什么。我应该提到我在代码中使用fork()。也许是原因。
我认为我的出口关闭了子进程,但是主进程继续运行。所以这就是为什么它给了我返回的值,而不是出口的值。
您的子进程以奇异值退出,但是您的主进程始终以0退出,这就是确定$?
的原因。
如果要让$?
作为子进程的退出值,则必须为wait()
,获取子进程的退出代码,然后使用它退出主进程。