[英]how to pass error message to file after invoking execvp in C
When I invoke execvp
with a command and its arguments, sometimes the command is not legitimate. 当我使用命令及其参数调用
execvp
时,有时该命令不合法。
For example, if I do this in my shell (bash shell) using my forked SON process: 例如,如果我使用派生的SON流程在我的外壳(bash外壳)中执行此操作:
$ ls ffdfdfd
then the output is: 那么输出是:
$ ls: cannot access ffdfdfd: No such file or directory
Now, I want to pass that exact message to a file. 现在,我想将确切的消息传递给文件。 I've tried with
perror
, this way: 我已经尝试过
perror
,这样:
void directErrors(char * arg)
{
perror(arg); // execute the problem to screen
// now execute the problem to file
FILE* myFile = fopen("errors.log", "a");
if(myFile == NULL)
{
perror("fopen");
exit(-1);
}
fprintf(myFile, "%s: %s\n", arg, strerror(errno));
fclose(myFile);
}
but all it does is write that command X
failed. 但是它所做的只是写命令
X
失败。
How can I direct the exact output that execvp
got after its invocation? 我该如何指示
execvp
调用后得到的确切输出?
In my code I invoke execvp
like this: 在我的代码中,我这样调用
execvp
:
executeCurrentCommand = execvp(*(arg)[0], *arg);
Remember that exec
works by completely replacing your program with the program you are exec'ing. 请记住,
exec
工作原理是用您正在执行的程序完全替换您的程序。 So, no code you write after an exec() call will ever run: 因此,您在exec()调用之后编写的代码将永远不会运行:
execvp(cmd, args);
/* This code is never reached. */
The only way exec
calls ever return is if the command you are trying to invoke cannot be run: for example if you try to exec a non-existent file or a file without execute privileges. exec
调用返回的唯一方法是无法运行您尝试调用的命令:例如,如果您尝试执行不存在的文件或没有执行特权的文件。
In your case, the command ( ls
) does exist and so the exec does succeed... which means that no code after it will ever be run. 在您的情况下,命令(
ls
) 确实存在,因此exec 确实成功了……这意味着之后的任何代码都不会运行。 The ls
command will generate the error message to stderr just as it always does. ls
命令将像往常一样生成错误消息给stderr。
If you want to capture the output of ls
you'll have to be more fancy. 如果要捕获
ls
的输出,则必须更加花哨。 For example you can open a file for append to the log file, then use dup()
to duplicate that as the stderr file descriptor, then do your exec call. 例如,您可以打开一个文件以追加到日志文件,然后使用
dup()
将其复制为stderr文件描述符,然后执行exec调用。 The new process will inherit that setting and all output that ls
sends to stderr will get appended to the log. 新进程将继承该设置,并且
ls
发送到stderr的所有输出将附加到日志中。 If you want to capture both stdout and stderr, dup them both. 如果要同时捕获stdout和stderr,请同时将它们都复制。 That's how the shell, etc. does it.
这就是外壳等的工作方式。
BTW, using *(arg)[0]
looks very bizarre to me: why do you use that? 顺便说一句,使用
*(arg)[0]
在我看来很奇怪:您为什么使用它? More reasonable would be (*arg)[0]
(I would think). 更合理的是
(*arg)[0]
(我认为)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.