#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cplist.h"
#include <sys/time.h>
#include <iostream>
#include <sys/wait.h>
#include <errno.h>
struct timeval start, end;
char *key;
int launch_children(cplist *head){
pid_t cpid;
double execution_times = 0;
if(cpid = fork() < 0 ){ // Important to trap errors
std::cerr << "ARGH I'm likely in trouble, get me out of here!" << std::endl;
exit(1); // Important to exit on errors
}else if (cpid == 0 ){
std::cout << "Child process "<< getpid() << ". Running grep on " << key << head->path << std::endl;
execlp("prog2b", "prog2b", "grep", "-R", key, head->path, NULL);
std::cerr << "Exec failed.. Why?" << std::endl;
exit(1); // VERY IMPORTANT - DON'T LET CHILD KEEP RUNNING
} else { // parent
head->cpid = cpid;
wait(NULL);
std::cout << "Child "<< cpid << "has terminated in " << execution_times;
}
}
int main(int argc, char *argv[]){
int i;
int j = 0;
cplist *head = (cplist*) malloc(sizeof(cplist));
head->path = NULL;
head->next = NULL;
if(strcmp(argv[1], "-v") == 0){
key = argv[2];
for(i = 3; i < argc; i++){
cpl_add(head, argv[i]);
j++;
}
} else {
key = argv[1];
for(i = 2; i < argc; i++){
cpl_add(head, argv[i]);
j++;
}
}
printf("key: %s\n", key);
launch_children(head);
return(0);
}
我的程序应该从命令行中获取键和路径值,然后子进程应使用'grep''-r'执行execlp,并将值传递给我。我正在努力使exec正常工作正确地。我在手册页上花了很多时间,试图让高管们更好地了解他们并测试其他高管,但是我陷入了困境。 exec进程将无法运行。这是一个示例,说明它现在如何工作:
当我从命令行运行:./prog2b 5678 /hw1/02/
时,我的输出是:
key: 5678
Child process 70788. Running grep on 5678 /hw1/02
Exec failed.. Why?
key: 5678
Child process 70789. Running grep on 5678 /hw1/02
Exec failed.. Why?
正确的输出应该是:
key: 5678
Child process nnnnn. Running grep -R 5678 hw1/02
../../hw1/02/nYyLimCI:5678
../../hw1/02/ANFGmj97:5678
../../hw1/02/oFrtX8Sy:5678
../../hw1/02/UrYt9aBz:5678
../../hw1/02/wE1AMVeh:5678
../../hw1/02/F6TGJEiJ:5678
../../hw1/02/v1HG6zmh:5678
../../hw1/02/YyOSKcJG:5678
Child process nnnnn has terminated in a.bbbbbb seconds
我知道exec失败,并且我尝试使用errno并输出“没有这样的文件或目录”。我不确定这是指什么。我也不太了解如何在exec中使用grep,我认为这可能是个问题。希望这将帮助我解决fork和exec的麻烦。我有一个头文件和_add和_dump的链接列表函数类,但我不认为这些是导致此错误的原因
我正在编写函数,该函数接受链表中的值,然后使用传递到命令行的参数分叉进程并执行新进程。这是我对于prog2b.cc的代码:...
errno
设置为ENOENT
(没有这样的文件或目录)的事实告诉您execlp()
无法找到可执行文件。