【发布时间】:2013-10-09 18:55:42
【问题描述】:
我正在分叉一个进程并使用execl 运行wc 命令。现在在正确的参数下,它运行良好,但是当我给出错误的文件名时,它会失败,但在这两种情况下,返回值
WEXITSTATUS(status)
始终为 0。
我认为我正在做的事情有问题,但我不确定是什么。阅读手册页和谷歌建议我应该根据状态代码获得正确的值。
这是我的代码:
#include <iostream>
#include <unistd.h>
int main(int argc, const char * argv[])
{
pid_t pid = fork();
if(pid <0){
printf("error condition");
} else if(pid == 0) {
printf("child process");
execl("/usr/bin/wc", "wc", "-l", "/Users/gabbi/learning/test/xyz.st",NULL);
printf("this happened");
} else {
int status;
wait(&status);
if( WIFEXITED( status ) ) {
std::cout << "Child terminated normally" << std::endl;
printf("exit status is %d",WEXITSTATUS(status));
return 0;
} else {
}
}
}
【问题讨论】:
-
你
#include <sys/wait.h>了吗? -
@KerrekSB:除非
<iostream>包含<sys/wait.h>(或<unistd.h>包含),否则如果不包含<sys/wait.h>,代码将无法编译。 (话虽如此,它在 Mac OS X 10.8.5 和 GCC 4.8.1 上编译正常,没有明确的<sys/wait.h>,这让我很惊讶!)printf()和cout的混合很奇怪,容我们说。它是 C++——只是。但只是而已。printf()消息应以换行符结尾。当我运行代码时,我得到:wc: /Users/gabbi/learning/test/xyz.st: open: No such file or directory和Child terminated normally和exit status is 1— 根据需要。 -
“...当我输入错误的文件名时...”请说明您指的是哪个文件名。
-
澄清一下,这一切都是 Xcode 的问题。当我从控制台运行相同的代码时,它没有任何问题。
标签: c++ c operating-system fork wait