验证码:
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()
失败。
有什么问题吗?
1条答案
按热度按时间fykwrbwg1#
以下拟议代码:
1.干净地编译
1.执行所需的功能
1.正确地等待子进程完成
1.包含所需头文件的
#include
语句现在,建议的代码:
结果输出为: