代码:
static void child() {
char* args[] = {"/bin/echo", "Hello World!", NULL};
printf("I'm child! My PID is %d.\n", getpid());
fflush(stdout);
execv("/bin/echo", args); // !!
err(EXIT_FAILURE, "execv() failed");
}
static void parent(__pid_t pid_c) {
printf("I'm parent! My PID is %d and my child's PID is %d.\n", getpid(), pid_c);
exit(EXIT_SUCCESS);
}
int main() {
__pid_t ret;
ret = fork();
if (ret == -1) {
err(EXIT_FAILURE, "fork() failed");
} else if (ret == 0) {
child();
} else {
parent(ret);
}
err(EXIT_FAILURE, "Shouldn't reach here");
}
结果:
I'm parent! My PID is 4543 and my child's PID is 4544.
I'm child! My PID is 4544.
在上面的代码中,我想将 child
进程替换为 /bin/echo
进程,但是 echo
不起作用。更准确地说,调用 execv()
失败。
问题是什么?
最佳答案
以下建议代码:
- 干净地编译
- 执行所需的功能
- 正确等待子进程完成
- 包含所需头文件所需的
#include
语句
现在,建议的代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <err.h>
static void child() {
char* args[] = {"/bin/echo", "Hello World!", NULL};
printf("I'm child! My PID is %d.\n", getpid());
fflush(stdout);
execv( args[0], args);
err(EXIT_FAILURE, "execv() failed");
}
static void parent(__pid_t pid_c) {
printf("I'm parent! My PID is %d and my child's PID is %d.\n", getpid(), pid_c);
wait( NULL );
exit(EXIT_SUCCESS);
}
int main() {
__pid_t ret;
ret = fork();
if (ret == -1) {
err(EXIT_FAILURE, "fork() failed");
} else if (ret == 0) {
child();
} else {
parent(ret);
}
err(EXIT_FAILURE, "Shouldn't reach here");
}
结果输出是:
I'm parent! My PID is 31293 and my child's PID is 31294.
I'm child! My PID is 31294.
Hello World!
关于调用 execv() 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56809245/