ANSI C - 执行进程、等待、删除文件
我正在尝试执行 LP 来打印 PDF 文档并等待它退出。后 它存在我正在尝试使用 unlink() 删除该文件;
然而,等待甚至在 execv 执行 LP 之前就完成了。我不太确定 如何处理这个问题以及为什么等待不等到 execv 完成。
还有其他方法可以实现此目的吗?
if(fork())
{
fprintf(stderr, "Executing command %s %s", "/usr/bin/lp", homedir);
char *const parmList[] = {"/usr/bin/lp", homedir, (char *)0};
execv("/usr/bin/lp", parmList );
}else
{
int pid, status;
fprintf(stderr, "Wait\n");
pid = wait(&status);
fprintf(stderr, "Finished waiting.\n");
unlink(homedir);
}
执行上述代码时,输出将如下所示:
Wait
Finished waiting.
Executing command /usr/bin/lp /home/user/Docs/test.pdf
/usr/bin/lp: Error - unable to access "/home/user/Docs/test.pdf" - No such file or directory
I am trying to execute LP to print a PDF document and wait for it to exit. After
it exists i am trying to delete the file with unlink();
However the wait finishes even before execv execute LP. I am not quite sure
how to handle this and why the wait isn't waiting till execv finishes.
Is there any other way to accomplish this?
if(fork())
{
fprintf(stderr, "Executing command %s %s", "/usr/bin/lp", homedir);
char *const parmList[] = {"/usr/bin/lp", homedir, (char *)0};
execv("/usr/bin/lp", parmList );
}else
{
int pid, status;
fprintf(stderr, "Wait\n");
pid = wait(&status);
fprintf(stderr, "Finished waiting.\n");
unlink(homedir);
}
When executing the above code the ouput would look like this:
Wait
Finished waiting.
Executing command /usr/bin/lp /home/user/Docs/test.pdf
/usr/bin/lp: Error - unable to access "/home/user/Docs/test.pdf" - No such file or directory
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
fork()
在子进程中返回零,在父进程中返回正值(假设 fork 成功),并且wait(...)
仅在以下情况下有意义父进程,因此您需要交换if
和else
块的内容。fork()
returns zero in the child process, and a positive value in the parent process (assuming the fork succeeds), andwait(...)
only makes sense in the parent process, so you need to swap the contents of yourif
andelse
blocks.