gpt4 book ai didi

c - Process fork 没有执行所需的代码

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:31 25 4
gpt4 key购买 nike

所以我正在尝试执行教授给我的这段代码。这非常简单。它 fork ,检查 fork 是否正常工作,然后在单独的文件中执行另一段代码。

出于某种原因,在我的 OS X 10.9.5 机器上,无法执行第二位代码。以下是这两个程序:

练习.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>


int main() {
pid_t child = fork();
if ((int)child < 0) {
fprintf(stderr, "fork error!\n");
exit(0);
} else if ((int)child > 0) {
int status;
(void) waitpid(child, &status, 0);
if (WIFEXITED(status)) {
printf("child %d exited normally and returned %d\n",
child, WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("\nchild %d was killed by signal number %d and %s leave a core dump\n",
child, WTERMSIG(status), (WCOREDUMP(status) ? "did" : "didn't"));
} else {
printf("child %d is dead and I don't know why!\n", child);
}
} else {
char *argv[] = { "./getcode" };
execve(argv[0], argv, NULL);
}

return 0;
}

和getcode.c

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>


int main() {
int rc = 256;
printf("I am child process %d\n", getpid());
while ((rc > 255) || (rc < 0)) {
printf("please type an integer from 0 to 255: ");
scanf("%d", &rc);
}
exit(rc);
}

我用命令编译它们:

gcc -Wall -pedantic-errors exercise.c -o exercise

gcc -Wall -pedantic-errors getcode.c -o getcode

不幸的是,我从子进程返回的唯一结果是返回码 0

./exercise
child 903 exited normally and returned 0

我很困惑。谁能帮忙?

编辑:好的,所以我按照要求包含了 perror("execve"),它返回了 execve: Bad address。那我该如何解决呢?

EDIT2:好的。我修好了它。我更改了上面代码的一部分以包含以下内容:

char *argv[] = { "./getcode",NULL };
execve(argv[0], argv, NULL);

空终止修复了 argv 问题。

最佳答案

您需要使用 NULL 元素终止 argv。来自 execve 手册页:

Both argv and envp must be terminated by a NULL pointer.

也不清楚 NULL 是否对 envp 参数有效。 Linux 手册页说

On Linux, argv can be specified as NULL, which has the same effect as specifying this argument as a pointer to a list containing a single NULL pointer. Do not take advantage of this misfeature! It is nonstandard and nonportable: on most other UNIX systems doing this will result in an error (EFAULT).

可能将 envp 指定为 NULL 同样是非标准的。如果您不需要指定环境,请使用 execv 而不是 execve。

您应该检查 execve 的返回值。并使用 errno 来确定原因。例如,使用 perror("execve") 可能会报错。

关于c - Process fork 没有执行所需的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25960340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com