调用execv()失败

tyky79it  于 2023-10-16  发布在  其他
关注(0)|答案(1)|浏览(109)

验证码:

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()失败。
有什么问题吗?

fykwrbwg

fykwrbwg1#

以下拟议代码:
1.干净地编译
1.执行所需的功能
1.正确地等待子进程完成
1.包含所需头文件的#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!

相关问题