问题描述
处理一个 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/wc
,execvpe
将调用该程序。
更正您的主程序
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
程序。