C语言 execve覆盖进程失败



我是并行处理的新手,并试图使用fork()来创建一个新的子进程,我想通过使用execute来覆盖这个进程。碰巧在我身上,执行("_filename",array, NULL)有时工作,但大多数时候,它无法覆盖过程并返回-1;我试图运行其他人的示例代码,但它在我的笔记本电脑上失败了,所以我想知道这是否是因为我的mac的配置?我对这个话题很陌生,希望我能在这里找到帮助,谢谢!

下面是我要运行的程序:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
int main(int argc, char **argv) {
// populate arraay with random numbers
int child_status;
pid_t pid;
int i;
pid = fork();
char *array[3] = {"Hello", "There", "Test"};
if (pid == 0) {
pid = execve("Process4", array, NULL);
exit(0);
}
int num = -1;
printf("What is 2 + 2");
while (num != 4) {
scanf("%d", &num);
if (num == 4) {
printf("You win                    n");
} else {
printf("%i incorrect - try again ", num);
printf("rbr");
}
}
wait(&child_status);
return (0);
}

对于Process4,我写在下面:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int secs = 0;
int main(int argc, char **argv) {
int i;
if (argc > 0) {
printf("The arguments supplied are:n");
for (i = 0; i < argc; i++) {
printf("%st", argv[i]);
}
} else {
printf("argument list is empty.n");
}
int j;
printf("n");
while (secs < 10) {
printf("Time:%in", secs);
fflush(0);
sleep(1);
secs++;
printf("rbr");
}
return 0;
}

我的process4应该能够接收传入的参数(作为第二个参数中的数组)并启动计时器。提前感谢您的帮助。

指定execve()参数的数组必须以NULL结尾

char *array[] = {"Hello", "There", "Test", NULL};
不是

char *array[3] = {"Hello", "There", "Test"};

最新更新