微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在子进程中使用execvp在c中显示新程序的返回值

如何解决在子进程中使用execvp在c中显示新程序的返回值

处理一个 uni 任务,我需要使用 1 个父进程来创建 3 个子进程,然后对每个子进程执行一些计算。我被困在孩子 2 上,我需要加载一个程序,该程序返回文本文件中的字数并将其显示在控制台上。

这是我的字数统计文件

wc.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main( int argc,char *argv[]) {
    char *wordCountFile = argv[1];
    printf("file name passed is %s\n",wordCountFile);
    printf("testing\n");
}

上面的文件实际上并没有计算文件中的字数,因为我只是在努力让它在控制台中显示

在我的主程序中

child2 = fork();
        wordCountFile = argv[1];
        char *cmd = "wc";
        char *args[3];
        argv[0] = "wc";
        argv[1] = wordCountFile;
        argv[2] = NULL;
        if (child2 == 0){
            printf("I am child two my pid is %d \n",getpid());
            printf("I will Now execute wc program to count all the words in file %s \n",wordCountFile);
            execvp(cmd,args);
            exit(3);
        }

我的输出如下:

I am child two my pid is 659
I will Now execute wc program to count all the words in file test.txt

我正在尝试让 wc 程序打印到控制台

我已经编译了 wc.c 并且程序与我的主代码在同一目录中。

解决方法

你的主程序有一些错误。您正在修改 argv 并将 args 传递给 execvpe,并且您正在调用 wc 程序而不是 ./wc。如果您使用的是 unix 系统,您可能拥有 /usr/bin/wcexecvpe 将调用该程序。

更正您的主程序

child2 = fork();
        wordCountFile = argv[1];
        char *cmd = "./wc";
        char *args[3];
        args[0] = "./wc";
        args[1] = wordCountFile;
        args[2] = NULL;
        if (child2 == 0){
            printf("I am child two my pid is %d \n",getpid());
            printf("I will now execute wc program to count all the words in file %s \n",wordCountFile);
            execvp(cmd,args);
            exit(3);
        } 

现在主程序会调用当前目录下的wc程序。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。