gpt4 book ai didi

c - execve() 仅在第一个循环上返回错误

转载 作者:行者123 更新时间:2023-11-30 17:27:18 25 4
gpt4 key购买 nike

我对此困惑了一段时间,现在我需要一些帮助。我正在尝试创建一个循环,该循环将 fork 子进程并通过 execve() 调用“echo hello”。

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

int main(int argc, char *argv[],char *envp[]){

int i = 0;

while(i<10){
pid_t pid;
pid = fork();

if(pid != 0){
int status;
waitpid(-1, &status, 0);
}

if(pid == 0) {
char *arg_array[2];
arg_array[0]="echo";
arg_array[1]="hello";
char filename[] = "/bin/echo";
if (execve(filename,arg_array,envp) == (-1)) {
printf("ERROR!\n");
exit(1);
}
}
i++;
}
}

起初,代码在第一次运行时失败,但随后的每次运行都成功。现在,在清理它以便在此处呈现之后,它根本不会成功 - 我得到的只是错误! x 10. 我肯定进一步破坏了某些东西,但我无法说出是什么。

这只是我在本网站上的第二个问题,因此,如果您对改进我的问题/建设性批评有任何建议,请分享!谢谢。

最佳答案

您错过了决赛NULL argv 的元素大批。使用perror execve之后还会给您正确的错误消息。因此:


char *arg_array[3];
arg_array[0] = "echo";
arg_array[1] = "hello";
arg_array[2] = NULL;

此外,您还缺少 #include <unistd.h>

关于c - execve() 仅在第一个循环上返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26452786/

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