C 等待(&;状态)始终返回0
我正在尝试获取子进程的退出状态,但始终获取0。 我做错了什么,不是这样吗 这是我的代码,tokens=commands数组。 谢谢 始终: 状态=0C 等待(&;状态)始终返回0,c,wait,C,Wait,我正在尝试获取子进程的退出状态,但始终获取0。 我做错了什么,不是这样吗 这是我的代码,tokens=commands数组。 谢谢 始终: 状态=0 我需要更改什么?您可能希望立即退出(255)以确保返回正确的状态。另外,wait很可能会获得EINTR。此外,返回状态只有在WIFEXITED(status)时才有意义,否则您不应该依赖它: #include <stdio.h> #include <unistd.h> #include <sys/types.h>
我需要更改什么?您可能希望立即退出(255)以确保返回正确的状态。另外,
wait
很可能会获得EINTR
。此外,返回状态只有在WIFEXITED(status)
时才有意义,否则您不应该依赖它:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <errno.h>
int execute(char** tokens)
{
pid_t pid;
int status;
pid = fork();
if (pid == -1)
{
fprintf(stderr,"ERROR: forking child process failed\n");
return -1;
}
// Child process
if (pid == 0)
{
// Command was failed
if (execvp(*tokens, tokens) == -1)
{
fprintf(stderr, "%s: command not found\n", *tokens);
exit(255);
}
}
else {
while (1) {
pid = wait(&status);
if (pid == -1) {
if (errno == EINTR) {
continue;
}
perror("wait");
exit(1);
}
break;
}
if (WIFEXITED(status)) {
int exitcode = WEXITSTATUS(status);
printf("%d\n", exitcode);
}
else {
printf("Abnormal program termination");
}
}
return status;
}
int main() {
char *args[] = {
"/bin/cmd_not_found",
"Hello",
"World!",
0
};
execute(args);
}
#包括
#包括
#包括
#包括
#包括
#包括
int执行(字符**令牌)
{
pid_t pid;
智力状态;
pid=fork();
如果(pid==-1)
{
fprintf(stderr,“错误:分叉子进程失败\n”);
返回-1;
}
//子进程
如果(pid==0)
{
//命令失败
if(execvp(*令牌,令牌)=-1)
{
fprintf(stderr,“%s:未找到命令”\n“,*标记);
出口(255);
}
}
否则{
而(1){
pid=等待(&状态);
如果(pid==-1){
如果(errno==EINTR){
继续;
}
佩罗(“等待”);
出口(1);
}
打破
}
如果(妻子退出(状态)){
int exitcode=WEXITSTATUS(状态);
printf(“%d\n”,exitcode);
}
否则{
printf(“异常程序终止”);
}
}
返回状态;
}
int main(){
字符*args[]={
“/bin/cmd\u未找到”,
“你好”,
“世界!”,
0
};
执行(args);
}
Zero在哪里?在pid
或状态下
?为什么不应该为0?0是一个非常好的退出状态。如果execvp
失败,您可能应该调用\u exit
,而不是返回。您应该将状态初始化为失败状态,因为您的代码路径允许返回未初始化的“success”值。“If wait()[…]由于向呼叫进程发送信号而返回,-1应返回,并且errno
设置为[EINTR]。wait(&status)
返回的值是多少?您可能需要一个围绕调用的循环,例如do{pid=wait(&status);}while(pid=-1&&errno==EINTR)
这是OP的“return255”,我想它应该是进程退出代码
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <errno.h>
int execute(char** tokens)
{
pid_t pid;
int status;
pid = fork();
if (pid == -1)
{
fprintf(stderr,"ERROR: forking child process failed\n");
return -1;
}
// Child process
if (pid == 0)
{
// Command was failed
if (execvp(*tokens, tokens) == -1)
{
fprintf(stderr, "%s: command not found\n", *tokens);
exit(255);
}
}
else {
while (1) {
pid = wait(&status);
if (pid == -1) {
if (errno == EINTR) {
continue;
}
perror("wait");
exit(1);
}
break;
}
if (WIFEXITED(status)) {
int exitcode = WEXITSTATUS(status);
printf("%d\n", exitcode);
}
else {
printf("Abnormal program termination");
}
}
return status;
}
int main() {
char *args[] = {
"/bin/cmd_not_found",
"Hello",
"World!",
0
};
execute(args);
}