代码:
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()失败了。
有什么问题吗?
发布于 2019-06-28 16:36:14
下列拟议守则:
#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!https://stackoverflow.com/questions/56809245
复制相似问题